2.5 Hello golang

Writing your first hello golang

Create an empty file hello.go, try to execute

touch hello.go
go run hello.go

Yields an error

can't load package: package main: 
gobook/main.go:1:1: expected 'package', found 'EOF'

answer:

In the language go, go all the source files must declare a particular packet belongs, at least a package main, main package name created for themselves.

1.1 Correct hello golang

Go code file, the program must specify the start function main (), as the car ignition switch.

Hello.go

package main    //声明为main包,即可以编译成二进制程序

import "fmt"    //导入fmt格式化包

func main(){fmt.Println("hello golang")}    //main主函数入口

run

go run hello.go

result

hello golang

However, the above is not beautiful, provides a formatting code commands Go

go fmt hello.go

After formatting, the following code style

package main

import "fmt"

func main() {
    fmt.Println("hello golang")    //调用fmt包下的Println函数
}

Guess you like

Origin www.cnblogs.com/open-yang/p/11256725.html