Home >Backend Development >Golang >Why Does My Go Program Show an 'undefined' Error When Calling a Function in a Separate File?
Go Program Function Ambiguity Resolved
In an attempt to evoke a function defined in a separate file, a Go program encountered an "undefined" error. The following code illustrates the scenario:
main.go
package main func main() { emp := NewEmployee() // Undefined error }
employee.go
package main type Employee struct { name string age int } func NewEmployee() *Employee { // Employee struct and function definitions } func PrintEmployee (p *Employee) { // Function definitions }
Upon running the program, the following error is returned:
undefined: NewEmployee
The error stems from improper file handling techniques. To resolve this:
Avoid using file arguments for go build or go install. For go run, while file arguments may be used, it's generally advisable to build a package using go run .. Alternatively, opt for go install or go build.
The above is the detailed content of Why Does My Go Program Show an 'undefined' Error When Calling a Function in a Separate File?. For more information, please follow other related articles on the PHP Chinese website!