iT邦幫忙

2021 iThome 鐵人賽

DAY 3
0
DevOps

"GoDevOps": Learn DevOps Tools with Go系列 第 3

[Golang] Deep into Hello World!

  • 分享至 

  • xImage
  •  

Let's start by understanding the hello.go example

package main

import (
	"fmt"

	"golang.org/x/example/stringutil"
)

func main() {
	fmt.Println(stringutil.Reverse("!selpmaxe oG ,olleH"))
}

hello.go include three parts: packages, import and func main().

packages

The first statement of every go source file must be a package declaration.
Package is a way for collecting related Go code together.
A packages can have many files inside of it. For example:

main.go

// main.go
package main
import (
	"fmt"
)

func main() {
	fmt.Println("Hello MAIN!")
}

help.go

// help.go
package main
import (
	"fmt"
)

func help() {
	fmt.Println("Help!")
}

There are two type of packages

  • Executable: Generate a file that we can run.
  • Reuseable: Code dependencies or libraries that we can reuse.

Use package name main to specify this package can be compiled and then executed. Inside the main package, it must has a func call 'main'

Other package name defines a package that cab be used as a dependency.
We will discuss how to use reuseable packages later.

import

Use to import code from other packages.
Although there are some standard librariessuch as math, fmt ,debug ... etc.
We still need to use import to link the library to our package.
you can find out more standard libraries on golang.org/pkg

Besides, you can import third party packages from internet as well.
for example import "golang.org/x/example/stringutil"
This required you to install the package via command go get <package> before building your own package.

func main()

The entry of our execuable code. This function is required for main package.


上一篇
[Golang] Go Installation and Basic Toolchain Introduction
下一篇
[Golang] Introduction to Variables
系列文
"GoDevOps": Learn DevOps Tools with Go11
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言