zoukankan      html  css  js  c++  java
  • 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, 报错:

  • 相关阅读:
    COM组件开发实践(七)---多线程ActiveX控件和自动调整ActiveX控件大小(上)
    A Complete ActiveX Web Control Tutorial
    C++使用VARIANT实现二维数组的操作
    用户自定义结构数据与VARIANT转换
    VS2008中使用JSONCPP方法小结
    HDOJ 2030 汉字统计
    HDOJ 1312 (POJ 1979) Red and Black
    POJ 1503 Integer Inquiry 简单大数相加
    POJ 1936 All in All
    枚举法
  • 原文地址:https://www.cnblogs.com/oxspirt/p/9341868.html
Copyright © 2011-2022 走看看