代码之家  ›  专栏  ›  技术社区  ›  AlikElzin-kilaka planben

为什么允许将字符串类型转换为字节片?[关闭]

  •  -2
  • AlikElzin-kilaka planben  · 技术社区  · 5 年前

    问题是在哪里定义这种转换以使其适用?在里面找不到 builtin.go .

    工作示例:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        s := "A string"
        myBytes := []byte(s)
        fmt.Println(s)
        fmt.Println(myBytes)
    }
    

    如果我更换 []byte(s) []int(s) 它在上失败 cannot convert s (type string) to type []int ,我理解为 int 不是 uint8/byte

    那么转换定义在哪里呢?

    1 回复  |  直到 5 年前
        1
  •  2
  •   Eli Bendersky    5 年前

    如果您对Go编译器/运行时中发生这种情况的位置感兴趣,请查看 runtime.stringtoslicebyte 功能: https://golang.org/src/runtime/string.go?s=4341:4393#L155

    go tool compiler -l -S <your-go-file.go> 去看看)

    [请注意,在编写本报告时,Go 1.15中是这样的,将来可能会发生变化]