如何在golang中使用自定义包? [英] How to use custom packages in golang?

查看:160
本文介绍了如何在golang中使用自定义包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Go中创建和使用自定义包。这可能是非常明显的,但我无法找到关于此的很多信息。基本上,我将这两个文件放在同一个文件夹中:

mylib.go

 包mylib 

类型SomeType结构{

}

main.go

  package main 

进口(
mylib


func main(){

}

当我尝试运行main.go 时,出现此错误:

  main.go:4:2:importmylib:can not find package 

我试着运行首先构建mylib.go ,但它看起来不像做任何事情(没有文件生成,没有错误信息)。因此,任何想法,我怎么能做到这一点?

首先,一定要阅读并理解如何编写Go代码文档。

实际答案取决于关于你的定制软件包的性质。



如果它的目的是为了一般用途,考虑使用所谓的Github代码布局。基本上,你让你的图书馆是一个单独的去获取 - 表项目。



如果你的图书馆是供内部使用的,您可以这样做:


  1. 将包含库文件的目录放在项目目录下。

  2. 在项目的其余部分,使用其相对于包含该项目的工作空间的根的路径引用该库。

演示:

  src / 
myproject /
mylib /
mylib.go
...
main.go

现在,在顶层 main.go ,你可以导入myproject / mylib,它可以正常工作。


I'm trying to create and use a custom package in Go. It's probably something very obvious but I cannot find much information about this. Basically, I have these two files in the same folder:

mylib.go

package mylib

type SomeType struct {

}

main.go

package main

import (
    "mylib"
)

func main() {

}

When I try to go run main.go, I get this error:

main.go:4:2: import "mylib": cannot find package

I've tried to run go build mylib.go first but it doesn't seem to be doing anything (no file generated, no error message). So any idea how I could do this?

解决方案

First, be sure to read and understand the "How to write Go code" document.

The actual answer depends on the nature of your "custom package".

If it's intended to be of general use, consider employing the so-called "Github code layout". Basically, you make your library a separate go get-table project.

If your library is for internal use, you could go like this:

  1. Place the directory with library files under the directory of your project.
  2. In the rest of your project, refer to the library using its path relative to the root of your workspace containing the project.

To demonstrate:

src/
  myproject/
    mylib/
      mylib.go
      ...
    main.go

Now, in the top-level main.go, you could import "myproject/mylib" and it would work OK.

这篇关于如何在golang中使用自定义包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆