我有2个兄弟档案:main和test_two。每个文件分别是main.go和test_two.go文件。在一个我有一个自定义结构,而在另一个我想运行一个函数与该结构作为一个参数。我收到了错误" undefined:Struct"。
package main
import "github.com/user/test_two"
type Struct struct {
Fn string
Ln string
Email string
}
func main() {
foo := new(Struct)
foo.Fn = "foo"
foo.Ln = "bar"
foo.Email = "foo@bar.com"
test_two.Fn(foo)
test_two.go:
package test_two
import (
"fmt"
)
func Fn(arg *Struct) {
fmt.Println(arg.Fn)
}
答案 0 :(得分:9)
要遵守的一些规则:
你可能想要这样的东西:
app/main.go
app/mypkg/mypkg.go
包含main.go的内容:
// Package main is your app entry point in main.go
package main
import (
"stackoverflow/packages/mypkg"
)
func main() {
foo := mypkg.Struct{
Fn: "foo",
Ln: "foo",
Email: "foo@bar.com",
}
mypkg.Fn(foo)
}
mypkg.go的内容:
package mypkg
import (
"fmt"
)
type Struct struct {
Fn string
Ln string
Email string
}
func Fn(s Struct) {
fmt.Printf("func called with %v\n", s)
}