Home > Backend Development > Golang > Why is my Go function undefined when called from a different file?

Why is my Go function undefined when called from a different file?

DDD
Release: 2024-12-14 10:33:12
Original
291 people have browsed it

Why is my Go function undefined when called from a different file?

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()
}
Copy after login

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!"
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template