• go 中的pacage 名称 和import {}中的名称


    参考: https://groups.google.com/forum/#!topic/golang-nuts/oawcWAhO4Ow

    Hi, 


    Nan Xiao <xiaona...@gmail.com> writes: 
    > (1) GOPATH="/root/go"; 
    > (2) There is a folder whose name is "wire" in /root/go/src; 
    > (3) There is a file(a.go) in wire folder: 
    > package shark 

    What you describe, is a package "shark", with the import path 
    "wire". So: 

    > (4) hello.go: 

    Try instead: 

    > package main 

    > import ( 
    >         "wire" 
    > ) 

    > func main() { 
    >         shark.Hello() 
    > } 

    And now you know, why there is the strong suggestion, to have the 
    package name and the last component of the import path the same. From 
    this package main, there is *no way* to deduce, that shark.Hello() is 
    from the package with import path "wire", except looking at the 
    sourcecode. 

    My suggestion is: 
    a) Name the folder /root/go/src/shark (import path "shark") and the package shark 
    b) Name the folder /root/go/src/wire (import path "wire") and the package wire 
    c) Name the folder /root/go/src/wire/shark (import path "wire/shark") and the package shark 

    So, you are confused by there being *three* concepts: 
    a) the import path 
    b) the location on disk 
    c) the package name 

    a and b are *strongly* related (location = $GOPATH/importpath). But c is 
    only related to a and b by convention. 

    Best, 

    Axel 

    -------------------------------------------------------------------------------------------------------------------------------------------

    import 中指定的名称,其实是 “包” 所在的路径(磁盘路径), package 的名称不一定要和所在的目录名称一样。

    main.go

    package main
    
    import "fmt"
    import (
    	// "../demo/f1"
    	"./f1"   //import这里的,其实是磁盘路径名。
    )
    
    func say() {
    	fmt.Println("say function call!")
    }
    
    func main() {
    	fmt.Println("hello, world")
    
    	say()
    	// fly()
    	p_f1.F1()   //这里的和文件里面的 package 定义的报名一致就可以了。不一定要和目录名f1 同名, 可以随便命名,如这里的p_f1.
    //但是同一个目录下,不用的文件中的 package 定义的包名 也只能有一个!!
    // f1.F2() }

      f1.go

    package p_f1
    
    import (
    	"fmt"
    )
    
    func F1() {
    	fmt.Println("package demo f1 func call")
    }
    

      f2.go

    package p_f1
    
    import (
    	"fmt"
    )
    
    func F2() {
    	fmt.Println("package f1 f2 func call.")
    }
    

      go run mian.go

     稍微改一下,如果把f2.go 的第一行 package p_f1 改为 f1 , 运行: go run main.go, 报错:

  • 相关阅读:
    PAT 1010. 一元多项式求导 (25)
    PAT 1009. 说反话 (20) JAVA
    PAT 1009. 说反话 (20)
    PAT 1007. 素数对猜想 (20)
    POJ 2752 Seek the Name, Seek the Fame KMP
    POJ 2406 Power Strings KMP
    ZOJ3811 Untrusted Patrol
    Codeforces Round #265 (Div. 2) 题解
    Topcoder SRM632 DIV2 解题报告
    Topcoder SRM631 DIV2 解题报告
  • 原文地址:https://www.cnblogs.com/oxspirt/p/9341868.html
Copyright © 2020-2023  润新知