Steps to declare a Go package: Use the package statement, followed by the package name (must be consistent with the source file name), to declare the package. When importing a package, use the import statement followed by the package name. When using symbols from a package, you need to use the package prefix.
#How to declare a package in Go language?
In the Go language, a package is composed of a set of related files, which defines code such as types, constants, variables, and functions. Each package has a unique package name that is used to identify and import code within the package.
Declaring a package
To declare a package, you need to use the package
statement at the beginning of the source file, followed by the package name:
package mypackage
Only one package can be declared in each source file, and the package name must be the same as the file name of the source file (without extension). For example, if the source file is named mypackage.go
, it should declare the package mypackage
.
Import package
To use code from other packages, you need to use the import
statement at the beginning of the source file, followed by the package name:
import "fmt"
fmt
Package defines functions for formatting output and input. After importing a package, you can use the symbols (types, constants, variables and functions) in the package, but you need to use their package prefix, for example:
fmt.Println("Hello, world!")
Practical case
Create a source file named main.go
, declare a package and use the fmt
package:
package main import "fmt" func main() { fmt.Println("Hello, world!") }
Compile and run the program:
$ go run main.go Hello, world!
Tip
util
or common
. .
operator to represent the current directory, such as import . "mylocalpackage"
. The above is the detailed content of How to declare a package in Go?. For more information, please follow other related articles on the PHP Chinese website!