您的位置:首页 > 编程语言 > Go语言

Go语言学习之Hello World(The way to go)

2017-02-21 14:33 976 查看
分析过Go语言为什么在中国格外的火,介绍过Go语言的前世今生,也与大家分享了Windows和Mac上如何进行环境变量的配置。

现在,终于可以开始Go之旅了。当然按照国际惯例,从Hello World开始吧!!!

Hello World例子

我们队Go中的hello world并不陌生,因为在测试开发环境的时候,我们就使用过,这里先贴上代码,再一点点进行分析:

package main

import "fmt"

func main() {
//The first go program
fmt.Println("Hello, World!")
}


从上面的简短代码中,我们可以看到一个go程序基本包含几个部分:

- package声明

- 导入packages

- 函数

- 变量

- 表达式

- 注释

下面就根据Hello World例子进行更深入的分析:

package main

main package is the starting point to run the program. Each package has a path and name associated with it.

main是一个特殊的package名字,GO的可执行程序必须在main package下

import “fmt”

“fmt” is a preprocessor command which tell the Go compiler to include files lying in package fmt.

Package fmt包含有格式化I/O函数,类似于C语言的printf和scanf。格式字符串的规则来源于C但更简单一些。

func main()

The next line func main() is the main function where program execution begins.

//The first go program

使用//或是 /**/ 进行注释,这跟C++ java中的注释是一致的

fmt.Println(…)

fmt.Println(…) is another function available in Go which causes the message “Hello, World!” to be displayed on the screen. Here fmt package has exported Println method which is used to display message on the screen.

// Println 在 Print 的基础上,再向 os.Stdout 中写入一个换行符

func Println(a …interface{}) (n int, err error)

Println以大写字符开始

Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means that a function or variable/constant is accessible to importer of the respective package.

源代码文件中,以大写字母开头的函数才会被导出(外部访问)

不使用分号进行结尾

好了,至此,我们把第一个go程序进行了详尽的分析。接下来更进一步,把上面提到的东西更深一点。

import用法

import的使用方法有两种:

第一

import "fmt"
import "math/rand"


第二

import(
"fmt"
"math/rand"
)


这里一定要注意,使用的是圆括号而不是花括号。

fmt介绍

官方文档:

https://golang.org/pkg/fmt/

Package fmt implements formatted I/O with functions analogous to C’s printf and scanf. The format ‘verbs’ are derived from C’s but are simpler.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: