文字゚灵感💋每天300字昨夜星辰,诗意人生

Go 语言之语言结构

2019-07-03  本文已影响1人  灰常出色

Go语言的结构有以上几个方面构成。

1.package XXX 表示的是当前的包名,表示当前的代码属于哪一个包。这里的包与C++中的namespace很类似,用来表示这部分代码的作用域,用来做隔离使用,允许不同的包内的函数名和变量名。另外Go语言中的包名可以被其他的包引用。

2.import (XXX)表示的是该部分代码依赖于那些外部的包内容。这里的语法与C++中的#include类似,不过C++中包含的是单个的.h文件,Go语言包含的确实包名。

3.可以定义全局变量,数据结构等。位置与C++类似,不过C++一般将数据结构的声明和实现分离,一部分放到.h文件中,一部分放到.cpp文件中。Go语言中并无特别要求。

4.定义和实现函数的部分,Go语言中可以单独定义函数,也可以在struct和interface中实现函数,这两者的名字稍微有些不同,前者叫函数,后者叫方法。这于C++中的函数于方法并无特别不同。
5.init函数,这个函数先于main函数执行,主要用于初始化程序执行之前的数据和回调函数等。C++中的初始化一般会在Class中的构造函数中完成。

6.main函数,这个函数是Go语言的程序入口函数。于C++中的main函数功能类似。

例子:

package main // 1.定义包名

import (         // 2.包含的其他的包
    "fmt"
)

var a int   // 3.定义全局变量和数据结构

func test(strMap map[int]string) bool {   // 4.定义函数

    fmt.Println("Hello, playground: test!", strMap)
    for p, _ := range strMap {
        strMap[p] = "Davis"
    }

    return true
}

func init() {  // 5. main包中的init函数,会在main函数之前调用
    fmt.Println("Hello, playground: init begin!")
    a = 10
    fmt.Println("Hello, playground: init end", a)
}

func main() { // 6. 程序的入口main函数
    fmt.Println("Hello, playground: main begin!")
    strMap := make(map[int]string)
    strMap[0] = "hello"
    strMap[1] = "world"
    test(strMap)
    fmt.Println("Hello, playground: main end!", strMap)
}

Output:

Hello, playground: init begin!
Hello, playground: init end 10
Hello, playground: main begin!
Hello, playground: test! map[0:hello 1:world]
Hello, playground: main end! map[0:Davis 1:Davis]

参考文档:

1.Go 程序的基本结构和要素:https://learnku.com/docs/the-way-to-go/the-basic-structure-and-elements-of-the-go-program/3583


灰子作于二零一九年七月三日。
【原创作品,欢迎分享,请勿转载,谢谢尊重!!】

微信公众号,欢迎关注:


微信.png
上一篇 下一篇

猜你喜欢

热点阅读