Go tutorial - 基础语法
keyword - Different from C/Cpp keyword
nil : 空 - C/Cpp: NULL/nullptr/0(old version)
var 自动变量 - Cpp:auto 编译时语义分析器会根据右半部分表达式确定该变量是什么类型。
type 类型定义关键字:
结构体定义:
type struct_name struct{...}
-- C/Cpp:
struct/class Object_Name{public/protect/private:...}
根据已有类型定义新类型/别名:
type type_name new_type_name
- tip:
//类型定义
type NewInt int
//类型别名
type MyInt = int
fmt.Printf("type of a:%T\n", a) //type of a:main.NewInt
fmt.Printf("type of b:%T\n", b) //type of b:int
-- C/Cpp
defind/typedef/using
定义接口:
type Person interface{
SayHello()
interface_func_name()
...
}
-- Cpp
virtual return_val_type func_name(...) (const/or null) = 0;
default impl: virtual return_val_type class_name::func_name(...){...}
virtual return_val_type func_name(...) (const/or null);
定义函数别名:
type handle_SayHello SayHello(str string)
-- Cpp:auto val_name = [](){} / = func_name(...);
-- Cpp:function<return_type*(...)> func_pakge_name=func_name(...);
struct
1.go 没有Cpp 中虚类的概念、没有虚表、虚指针,也没有继承这一概念。访问控制只有private/public.在go结构体中成员首字母大写表示这个方法或者属性对外开放.
2.go 结构体成员仅能是属性字段,不能是函数声明。对应结构体的成员函数定义生命见下:
type myStruct struct {
age int
Name string
}
成员临时初始化(键值对形式):
p5 := myStruct {
age: 18,
name: "小王子",
}
成员临时初始化(initiration_list形式):
p5 := myStruct {
18,
"小王子",
}
构造函数:
func Func_Name(...) *struct_name {
return &struct_name{
// to do
...
}
}
成员函数:
func (val_name struct_name) Func_Name(...){
}
tip: 对于结构体成员方法接收者什么时候使用指针:
1. 需要修改接收者中的值
2. 接收者是拷贝代价比较大的大对象
3. 保证一致性,如果有某个方法使用了指针接收者,那么其他的方法也应该使用指针接收者
3.go 结构体成员可是匿名的 -- 没有成员名只有成员类型
type myStruct struct{
int // anonymous property
string // anonymous property
}
obj1 := myStruct{
12,
"haha"
}
// visit
obj1.int, obj1.string
interface
func
continue
break
if
for
while
switch - case
defer
go
error
select