Golang自定义结构体未定义,无法正确导入。

huangapple go评论87阅读模式
英文:

golang custom struct undefined, can't import correctly

问题

我有2个兄弟文件:main和test_two。每个文件中分别有main.go和test_two.go文件。其中一个文件中有一个自定义结构体,而另一个文件中我想要运行一个以该结构体作为参数的函数。我得到了错误信息"undefined: Struct"。

main.go文件内容如下:

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)
}
英文:

I've got 2 sibling files: main and test_two. In each is the file main.go and test_two.go respectively. In one I've got a custom struct and in the other I want to run a function with that struct as a param. I'm getting the error "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)
}

答案1

得分: 21

一些生活准则:

  • 不要在主函数中定义类型(通常情况下)
  • 不要尝试在其他包中导入主函数
  • 不要尝试双向导入(导入循环)
  • 总是从低级别导入到高级别(例如从 mypkg 导入到 main)
  • 所有文件夹都是包,将相关的数据/函数放在其中,并给它们起一个好名字

你可能想要像这样组织代码:

app/main.go
app/mypkg/mypkg.go

main.go 的内容如下:

// Package main 是你的应用程序的入口点(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("函数调用参数:%v\n", s)
}
英文:

Some rules to live by:

  • Don't define types in main (usually)
  • Don't try to import main in other packages
  • Don't try to import both ways (import cycle)
  • Always import from a lower level into a higher one (so mypkg into main)
  • All folders are packages, put related data/functions in them and name them well

You probably want something like this:

app/main.go
app/mypkg/mypkg.go

with contents for 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)
}

Contents for 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)
}

huangapple
  • 本文由 发表于 2017年3月17日 22:07:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/42859693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定