Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang custom struct undefined, can't import correctly

Tags:

go

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 = "[email protected]"
    test_two.Fn(foo)

test_two.go:

package test_two

import (
    "fmt"
)

func Fn(arg *Struct) {
    fmt.Println(arg.Fn)
}
like image 424
jj1111 Avatar asked Mar 17 '17 14:03

jj1111


1 Answers

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: "[email protected]",
    }
    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)
}
like image 178
Kenny Grant Avatar answered Sep 17 '22 18:09

Kenny Grant