go mistakes

1. map一定要初始化,slice可以不用初始化
2. pointer一定要初始化
var c *Course => must init => c = &Course{} or new(Course)
3. for-loop的临时变量是一个值会变化的变量

var out []*int
for i:= 0; i<3; i++{
// 保存的是i的地址,但是i最后会变成3,slice里全部是3
    out = append(out,&i)
}

=> tmp := i
out = append(out,&tmp)
// 1. use tmp

for _,id := range goodsId{
    tmp := id
    go func(){
    输出tmp
    }()
}        


// 2. use pass by value

go func(id uint64){
    print id
}(id)

4. generics

function:

func Add[T int|int32|float32|float64|uint64](a,b T) T{
    return a+b
}

Add[int](1,2)

substitution:interface{}

func IAdd(a,b interface{}) interface{}{
    switch a.(type){
    case int:
        return a.(int) + b.(int)
    case int32:
    return ...
    }
   return nil
}

IAdd(1,2).(int)    

 map

type MyMap[KEY int | string, Value float32 | float64] map[KEY]Value

func main() {
    mp := MyMap[int,float32]{
        
    }
}

struct

type Men struct {
}

type Women struct {
}

type Company[T Men|Women] struct {
    Name string
    CEO T 
}
 c := Company[Men]{
    "myname",
     Men{},
 }

chan

type MyChannel[T int|string] chan T

nestedType

type NestType[T int | string, S []T] struct {
    A T
    B []T
}
n := NestType[int, []int]{
    12,
    []int{1, 2, 3},
}

 generics 错误用法

1:T不能单独使用,一定是type内的构成是T

type CommonType[T int|string] T
=> type CommonType[T int|string] []T

 

2:指定指针类型要用interface{}包裹

type CommonType[T interface{*int} | string] []T

3.匿名结构体不支持泛型
4.T不支持 swtich T.(type)
=>

v := reflect.ValueOf(a)
switch v.Kind(){
  case reflect.Int:
  return a.(int) + b.(int)
}

 

posted @ 2024-06-22 10:17  PEAR2020  阅读(1)  评论(0编辑  收藏  举报