Go 语言入门指南:基础语法和常用特性解析 | 青训营

88 阅读2分钟

Go 语言入门指南:基础语法和常用特性解析 | 青训营

作者:LoHhhha 时间:2023.8.16

引言

本文使用go语言的语法特性与C++pythonjava作对比,以提升理解。

变量定义

go语言是一门强类型语言,与C++一样,但其变量的数据类型是由程序员指定或者由编译器推测得出,相当于C++中的auto var=xxx,在编译器完成对变量数据类型的确定。

常量的定义只需要附加上const

var num int
num=123
// 等效于以下两种
num int:=123
num:=123

for语句

C++类似,但又有点像python的语法,go中的for语句相当之有意思。

for 表达式 {}来表示C++中的while语句

// C++
while(x<n){
    x++;
}
​
// go
for x<n{
    x++;
}
​
// C++
while(true){
    /**/
}
​
// go
for {
    /**/
}

for 表达式;表达式;表达式 {}来表示C++for语句

// C++
for(int i=0;i<n;i++){
    /**/
}
​
// go
for i:=0;i<n;i++{
    /**/
}

for 变量 := range 可迭代的对象 {}来完成遍历

// C++
vector<int>arr;
map<int,int>hash;
for(auto &num:arr){
    /**/
}
for(auto &[val,f]:hash){
    /**/
}
​
// go
arr:=make([]int,10)
hash:=make(map[int]int)
for idx,num:=range arr{
    /**/
}
for val,f:=range hash{
    /**/
}

if语句

if语句与python基本一致,但表达式与java一致需要以bool数据类型表示。

if x==0 {
    /**/
}
​
// 附加语句
if num,err:=get();err!=nil{
    /**/
}

switch语句

与其他不一样,go分支默认带break,只会进入第一个满足的分支执行完成后退出。switch后不一定需要接表达式,可以在switch体内给出表达式且可以不相关。

switch 表达式 {
case 1:
case 2:
...
default:
}
​
switch {
case 表达式1:
case 表达式2:
...
default:
}

函数声明

C++中,想传递一个函数,我们需要引入lambda表达式。

// 非递归
auto func_cpp_0=[&](int x,int y){
    return x+y;
};
// 递归
function<int(int,int)>func_cpp_1=[&](int x,int y){
    if(y==0)return 1;
    else if(y==1)return x;
    int half=func_cpp_1(x,y/2);
    return half*half*(y%2?x:1);
};

但在go我们只需要与函数定义一样就可以了。

而且我们可以直接返回多个变量,也支持类似python**操作来获取不定量的参数。

  • 函数定义

    func func_name(avg) return_vars {
        /**/
    }
    
  • 传递一个函数

    f:=func (avg) return_vars{
    	/**/
    }