Home >Backend Development >Golang >Why Does My Go Program Show an 'undefined' Error When Calling a Function in a Separate File?

Why Does My Go Program Show an 'undefined' Error When Calling a Function in a Separate File?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-17 16:17:09404browse

Why Does My Go Program Show an

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:

Source Code

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
}

Error

Upon running the program, the following error is returned:

undefined: NewEmployee

Solution

The error stems from improper file handling techniques. To resolve this:

  • Use go build or go install within the package directory.
  • Alternatively, provide an import path for the package.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn