Can Golang remove the package name?

Guanhui
Release: 2020-06-17 09:34:50
Original
3285 people have browsed it

Can Golang remove the package name?

#Can Golang remove the package name?

Golang cannot remove the package name. The package name is a way of managing and organizing code similar to a namespace. There are two types of Golang packages, one is the "main" package, This package can have only one "main" function, which is also the entry point of the program. The other is a non-"main" package.

Simple example

➜  golang echo $GOPATH
/Users/master/golang
➜  golang pwd
/Users/master/golang
➜  golang tree
.
├── bin
├── pkg
└── src
    └── demo
        └── main.go

4 directories, 1 file

➜  demo cat main.go
package main

import (
    "fmt"
)

func main() {
    fmt.Println("hello world")
}

➜  demo go run main.go
hello world
Copy after login


From the directory above As can be seen from the structure, the GOPATH is /Users/master/golang. Created a project demo within src. There is a main.go file in the demo. The first line of main.go declares that this is a main package, so a main function can be defined. Use go run to compile and run main.go.

Custom package (package)

go uses package to manage source files. The package must be in a folder, and there can only be one package in a folder, but a folder can have multiple files. Customize a package below.

➜  demo tree
.
├── main.go
└── service
    └── http.go
1 directory, 2 files
➜  demo cat service/http.go
package api
import "fmt"
func HandleReq(){
    fmt.Println("api - http.go Handle Request")
}
➜  demo cat main.go
package main
import (
    "fmt"
    "./service"
)
func main() {
    fmt.Println("hello world")
    api.HandleReq()
}
Copy after login

Recommended tutorial: "Go Tutorial"

The above is the detailed content of Can Golang remove the package name?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!