dt1888 2017-03-17 14:07
浏览 169
已采纳

golang自定义结构未定义,无法正确导入

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条回答 默认 最新

  • duan02468 2017-03-17 14:34
    关注

    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
    ", s)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条