[英]Protocol buffers in Go: cannot find package
syntax = "proto3"; package tutorial; message Person { string name = 1; ... }
這正是發生的事情:我指定--go_out
與我的原型定義相同:( protoc --go_out=. addressbook.proto
)
然后在同一個文件夾中,我用這些簡單的行創建了一個 test.go:
package main
import "tutorial"
但是go build test.go
返回錯誤:
test.go:3:8: cannot find package "tutorial" in any of:
/usr/local/go/src/tutorial (from $GOROOT)
/home/vagrant/go2/src/tutorial (from $GOPATH)
然后我改變test.go
到這個:
package main
import "protobufs/tutorial"
並收到此錯誤:
test.go:3:8: cannot find package "protobufs/tutorial" in any of:
/usr/local/go/src/protobufs/tutorial (from $GOROOT)
/home/vagrant/go2/src/protobufs/tutorial (from $GOPATH)
但如果我將導入更改為:
package main
import "protobufs"
它發現該位置有一個“教程”包:
test.go:3:8: found packages tutorial (addressbook.pb.go) and main (list_people.go) in /home/vagrant/go2/src/protobufs
我究竟做錯了什么 ? 為了使這項工作正常進行,導入應該如何?
謝謝 !
僅供參考:我的 go env 的一個片段:
GOARCH="amd64"
GOBIN="/home/vagrant/go2/bin"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/vagrant/go2"
GORACE=""
GOROOT="/usr/local/go"
這個問題說明我對 Go 的封裝缺乏了解。 經過一些閱讀,這是我的結論/規則:
1. 每個文件夾一個包:“ abc ”目錄下的所有.go文件將表示package abc
2.你不能在同一個文件夾里有包main
和包abc
3. go install
在$GOPATH/pkg/GOOS_GOARCH/<path_to_abc_excluding_abc>
創建包對象abc.a
4. 對於文件夾$GOPATH/src/x/y/z/foo/
的包main
然后go install
編譯並在$GOPATH/bin
安裝一個名為foo
(路徑中最后一個目錄的名稱)的可執行文件
現在,回到最初的問題: $GOPATH/src/protobufs
目錄包含多個包:
- 帶有包名tutorial
的編譯后的 protobuf 和
- test.go
的main
包
這與上面列出的規則相矛盾。
我相信一種優雅的解決方案是:
- 假設我在$GOPATH/src/protobufs
- 創建一個名為tutorials
的子目錄
- 在該protoc --go_out=./tutorial ./addressbook.proto
安裝已編譯的 protobuf: protoc --go_out=./tutorial ./addressbook.proto
- test.go
現在可以有package main
並import "protobufs/tutorial"
感謝您走上正軌!
檢查GO 工作區:
A workspace is a directory hierarchy with two directories at its root:
src contains Go source files, and
bin contains executable commands.
本教程基於這種結構,即,
src/
github.com/protocolbuffers/protobuf/examples/
tutorial/
addressbook.pb.go
list_address.go
在該教程的makefile中,它通過pb.go
在examples
目錄下生成pb.go
:
mkdir -p tutorial
protoc $$PROTO_PATH --go_out=tutorial addressbook.proto
在add_person.go 下,它只是假設導入路徑在worksapce/src
,也就是上面提到的$GOPATH/src
:
import (
....
pb "github.com/protocolbuffers/protobuf/examples/tutorial"
// find through $GOPATH/src/github.com/protocolbuffers/protobuf/examples/tutorial
)
你需要做的是設置正確的GOPATH
並在$GOPATH/src
下生成那個pb.go
protoc -I=. --go_out=/Users/guihaoliang/Playground/go/my_workspace/src addressbook.proto
哪里.
指的是addressbook.proto
所在的位置。
GOPATH
工作區將被go 模塊取代,因此您不必維護src
和bin
結構。 protobuf 示例沒有使用新的模塊結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.