-2

I'm new to golang and could not find a good answer.

Problem: I have two files in the same folder that belong to the main package called main.go and my_type.go. The former includes main func and uses the type defined in the second file. The type is just a simple string array i.e. type myType [] string. Now if I understand correctly, types and funcs belonging to the same package don't need imports and by convention are started with lower case letters. This said, go run/build main.go spits out the error "undefined" for the type. The only way it works is by specifying both files or use a wild card. Is this the expected behavior? I've also started using vs.code and wonder if there's a way to configure running this properly in vs.code

Thanks in advance!

Sample error:

go build main.go
# command-line-arguments
./main.go:17:11: undefined: myType
farbo
  • 1
  • 1
  • `go build main.go` only attempts to build `main.go`, which doesn't include `my_type.go`. You need to build both files, either with `go build main.go my_type.go`, or preferably just `go build` from the root directory. – Gavin May 19 '23 at 19:01

1 Answers1

0

I would just use go build alone as follows

example> dir
19/05/2023  19:50               146 main.go
19/05/2023  19:48                39 mytype.go
example> type main.go
package main
import (
        "fmt"
)
func main() {
        var a myType
        a = append(a, "foo")
        a = append(a, "bar")
        fmt.Printf("%#v\n", a)
}
example> type mytype.go
package main
type myType  []string
example> go mod init
go: creating new go.mod: module example
go: to add module requirements and sums:
        go mod tidy

example> go mod tidy
example> go build
example> example
main.myType{"foo", "bar"}

If you just specify go build main.go it won't take into account the other file.

You can also try go run main.go mytype.go but I habitually just use either go build or go install. I typically have a separate directory per project executable.

RedGrittyBrick
  • 3,827
  • 1
  • 30
  • 51