Undefined Function Defined in Different File
You are attempting to call a function named NewEmployee from a different file, but you receive an "undefined" error. This error is caused by an incorrect way of building or running the Go program.
To resolve this issue, avoid using file arguments for go build or go install, and instead build the package using go run ..
Here's how you can fix your code:
main.go:
package main import "package/employee" func main() { emp := employee.NewEmployee() }
employee.go:
package employee type Employee struct { name string age int } func NewEmployee() *Employee { p := &Employee{} return p } func PrintEmployee(p *Employee) { return "Hello world!" }
By following these instructions, you can correctly build and run your Go program, allowing functions to be called from different files within the same package.
The above is the detailed content of Why is my Go function undefined when called from a different file?. For more information, please follow other related articles on the PHP Chinese website!