dongyan7950 2016-05-19 13:13
浏览 94

如何将Go代码转换为库?

I know how to make a function that adds up all the parameters given to it and one for subtraction and I wanted to make a simple math library for adding and subtracting and multiplying and dividing, but my internet searches for how to compile into a library came up with no results. I would like to know if there is a way to make a .go into a library and if so how do you do it. I am still very new to Go. If you know how to please tell me

  • 写回答

1条回答 默认 最新

  • douyan4958 2016-05-19 13:45
    关注

    If you run go install on your package, it will create a static library with the name of that package for you, and place it in your GOPATH/pkg/ARCH/packageName/packageName.a. For example, if you have your $GOPATH set as /home/yourname/go, you can create the following file:

    /home/yourname/go/src/myMath/myMath.go

    with the content of:

    package myMath
    
    func MyAdd(/* .... */) { // Capatalize the name of the function to allow it to be accessible from outside of this package
       // Do stuff
    }
    

    Now, if you do a go install, you will have a myMath.a library in the directory above.

    To use this library from another go package, myStats say, you can do the following:

    package myStats
    
    import "myMath" // import your library. notice the "" around the name
    
    func someFunction(/* .... */) {
       r := myMath.MyAdd(/* ..... */)
    }
    

    Notice again that you have to capitalized the name of the functions you wish to be used from outside of your package. For example, if your add function was called myAdd, then it would not been accessible from myStats even if you do import the myMath package.

    Edit fixed some errors based on the comments from @icza, below.

    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装