V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
LeegoYih
V2EX  ›  Go 编程语言

Go 有哪些奇技淫巧

  •  
  •   LeegoYih ·
    yihleego · 2023-03-21 12:33:44 +08:00 · 2803 次点击
    这是一个创建于 395 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如[]T[]any,只能通过遍历显式类型转换吗?有没有其他方法。

    func toAnyArray[T any](s []T) []any {
        t := make([]any, len(s))
        for i, v := range s {
            t[i] = v
        }
        return t
    }
    
    6 条回复    2023-03-30 20:37:21 +08:00
    caotian
        1
    caotian  
       2023-03-21 13:12:02 +08:00
    试试 lo 库
    0o0O0o0O0o
        2
    0o0O0o0O0o  
       2023-03-21 13:25:26 +08:00 via iPhone   ❤️ 3
    qieqie
        3
    qieqie  
       2023-03-21 14:14:42 +08:00   ❤️ 1
    转[]any/ {}interface 比较特殊,其它类型可以用 reflect.SliceHeader 之类的奇技淫巧
    https://github.com/golang/go/wiki/InterfaceSlice
    keakon
        4
    keakon  
       2023-03-21 15:31:02 +08:00
    如果类型兼容,用 unsafe.Pointer 转,但是 []any 不行

    a := []int{1, 2, 3}
    b := *(*[]uint)(unsafe.Pointer(&a))
    fmt.Println(b)
    c := *(*[]float32)(unsafe.Pointer(&a))
    fmt.Println(c)
    d := *(*[]float64)(unsafe.Pointer(&a))
    fmt.Println(d)
    e := *(*[]any)(unsafe.Pointer(&a))
    fmt.Println(e)

    如果是做接口的话,不建议用 []any ,直接用 any ,然后做类型检查,文档中注明比较好。
    LeegoYih
        5
    LeegoYih  
    OP
       2023-03-21 19:24:55 +08:00
    @keakon 谢谢,是调用方,实际场景是调用 sql.Stmt 的 Query 方法`func (s *Stmt) Query(args ...any) (*Rows, error)`
    暂时先不用泛型了吧🤣
    guonaihong
        6
    guonaihong  
       2023-03-30 20:37:21 +08:00
    Copilot, 回车工程师的诞生。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2695 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 15:04 · PVG 23:04 · LAX 08:04 · JFK 11:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.