Golang tutorial for C++ Programmers | Go 语言速成 | 3分钟学会 Go 语言 | Go 语言教程给 C++ 经验

  • map: map[key]value
  • 用 append 和 slice 实现 queue。
  • 用 make 造数组

首先花几秒钟浏览一下 Go 的语法:

Learn Go in Y Minutes (learnxinyminutes.com)

Go for C++ prgm

Go for C++ developers (golang.org)

看完后下面花两分半钟总结一下 Go 语言的速成:

Go 核心

  • array = 数组
  • slice = span<T>/basic_string_view<T> + vector<T>
  • goroutine + (channel = MQ)
  • GC
  • defer = RAII on_scope_exit
  • interface
  • reflection
  • 值 + 指针 + 特殊类型引用(特殊类型实际是 wrap 的一个 view 的 passed by value,just like java or string_view)

Go 一览

  • Go 用 GP interface
  • Go 用增量式 GC (三色标记 mark+sweep)
  • Go 有指针,没有运算。
  • Go 没有 class,有 type
  • Go 使用后置类型声明。
  • Go 的 if 可以写小括号或者没有小括号,for 不能写小括号,因为小括号等于是一个表达式,for 不是一个表达式。
  • Go 的 switch case 就是 if else 的语法糖,用 fallthrough 实现 C 不加 break 的效果。
  • Go 的字面常量和 const 是 untyped 的,因此可以和各种而言的东西结合。
  • Go 的 new = malloc + bzero,make = 对特定类型(slice、map 等)调用初始化。
  • Go 手写 thiscall 指针或者接受一个值实现 . 成员函数,是语法糖,同时也是区分 const ref 和 lavalue ref 的区别,value 的 receiver 会复制。。。
  • Go 的 interface 等于 C++ 的模板 constraint。
  • Go slice = pointer + capacity + length = vector + shared vector view。
  • Go 数组总是复制。
  • Go 参数应该用 slice
  • String 是 immutable 的
  • maps 是 unordered_map
  • GMP = Goroutine + Machine(Os thread) + Processor (Go 的 worker)

  • maps、channels 是 pass by reference 的。
  • Go 采用 package 而不是头文件
  • Go 不支持函数重载(所以没有 min max)。
  • Go 用 nil 而不是 null。
  • Go range = range based for。
  • Go 用 _ 忽略,如果 define 但不用会报错,可以用 _ = x 来避免 x  used。
  • Go 的 type a b 等于 typedef。
  • Go 的变量声明:

Go                  

        C++

var v1 int        

int v1;

var v2 string   

const std::string v2;  (approximately)

var v3 [10]int

 int v3[10];

var v4 []int    

 int* v4;  (approximately)

var v5 struct { f int }

 struct { int f; } v5;

var v6 *int       

 int* v6;  (but no pointer arithmetic)

var v7 map[string]int 

 unordered_map<string, int>* v7;  (approximately)

var v8 func(a int) int  

 int (*v8)(int a);

来自 <https://www.cs.cmu.edu/afs/cs.cmu.edu/academic/class/15440-f11/go/doc/go_for_cpp_programmers.html>

Go 不自由

  • Go 限制了大小写字母做 public 和 private
  • Go 限制了括号的语法,必须大括号不换行,for 不能写小括号。
  • Go 不用写分号。
  • Go 没有 while 循环。
  • Go 的 const 是真的 const 不是 view 的 const。
  • Go 不支持 implicit 转换
  • Go 没有继承只有组合,但是有 embedded 实现类似继承的语法糖。
  • Go 没有 -> 运算符,箭头运算符用来给 channel 用了。

Go Go GO

  • Go 有匿名函数,直接写 fun 就行了。
  • go XX(args...) 实现 goroutine = std::jthread jt(XX, args...);
  • channel 需要用 Name chan Type 指定,采用 make 制造。
  • channel = UNIX pipe = MQ。
  • channel 使用 <- 来接受和传递内容。

好了,看到这里你已经完全掌握 Go 了,现在我们用 Go 实现一个 Go Raft  吧!

Raft Paper

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值