2:go的并行机制并不是一般的线程,通过channel和goroutine来实现,比线程还要轻量级很多,所以go适合高并发的服务器端
3:go是系统级别的语言,相当于c语言,java c#都是算比较高级的语言,这个不太好比,效率的话目前确实是要高一些,而且不需要外部依赖,所以go还是很强大的
用golang解析二进制协议时,其实没必要管结构体的字段的对齐规则,何况语言规范也没有规定如何对齐,也就是没有规则。用encoding/binary.Read函数直接读入struct里就行,struct就像c那样写type Data struct {
Size, MsgType uint16
Sequence uint32
// ...
}
golang编译器加不加padding,Read都能正常工作,runtime知道Data的布局的,不像C直接做cast所以要知道怎样对齐。
用unsafe.Alignof可以知道每个field的对齐长度,但没必要用到。
package main
/*
#include <stdint.h>
#pragma pack(push, 1)
typedef struct {
uint16_t size
uint16_t msgtype
uint32_t sequnce
uint8_t data1
uint32_t data2
uint16_t data3
} mydata
#pragma pack(pop)
mydata foo = {
1, 2, 3, 4, 5, 6,
}
int size() {
return sizeof(mydata)
}
*/
import "C"
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"unsafe"
)
func main() {
bs := C.GoBytes(unsafe.Pointer(&C.foo), C.size())
fmt.Printf("len %d data %v\n", len(bs), bs)
var data struct {
Size, Msytype uint16
Sequence uint32
Data1 uint8
Data2 uint32
Data3 uint16
}
err := binary.Read(bytes.NewReader(bs), binary.LittleEndian, &data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", data) // {1 2 3 4 5 6}
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, data)
fmt.Printf("%d %v\n", buf.Len(), buf.Bytes()) // 15 [0 1 0 2 0 0 0 3 4 0 0 0 5 0 6]
}