The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
LeegoYih

Go 有哪些奇技淫巧

  •  
  •   LeegoYih ·
    yihleego · Mar 21, 2023 · 3898 views
    This topic created in 1332 days ago, the information mentioned may be changed or developed.

    比如[]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 replies  •  2023-03-30 20:37:21 +08:00
    caotian
    caotian
    Mar 21, 2023
    1
    试试 lo 库
    qieqie
    qieqie
    Mar 21, 2023❤️1
    3
    转[]any/ {}interface 比较特殊,其它类型可以用 reflect.SliceHeader 之类的奇技淫巧
    https://github.com/golang/go/wiki/InterfaceSlice
    keakon
    keakon
    Mar 21, 2023
    4
    如果类型兼容,用 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
    LeegoYih
    OP
    Mar 21, 2023
    5
    @keakon 谢谢,是调用方,实际场景是调用 sql.Stmt 的 Query 方法`func (s *Stmt) Query(args ...any) (*Rows, error)`
    暂时先不用泛型了吧🤣
    guonaihong
    guonaihong
    Mar 30, 2023
    6
    Copilot, 回车工程师的诞生。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2291 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 13:39 · PVG 21:39 · LAX 05:39 · JFK 08:39
    ♥ Do have faith in what you're doing.