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

新手求教一个类型断言的问题

  •  
  •   inori · Jun 22, 2020 · 2822 views
    This topic created in 2171 days ago, the information mentioned may be changed or developed.
    我理解 go 断言返回的应该是对应类型的对象,比如说
    package main

    import (
    "fmt"
    )

    func findType(i interface{}) {
    switch x := i.(type) {
    case int:
    fmt.Println(x, "is int")
    case string:
    fmt.Println(x, "is string")
    case nil:
    fmt.Println(x, "is nil")
    default:
    fmt.Println(x, "not type matched")
    }
    }

    func main() {
    findType(10) // int
    findType("hello") // string

    var k interface{} // nil
    findType(k)

    findType(10.23) //float64
    }

    这里 x 应该是具体类型的值 10, "hello"之类的,为什么可以和 int string 这些 case 匹配呢?
    4 replies    2020-06-22 16:58:16 +08:00
    Vegetable
        1
    Vegetable  
       Jun 22, 2020
    我去还能这么写...我以前都是判断好了再转一次
    whoami9894
        2
    whoami9894  
       Jun 22, 2020
    val.(type)是类型断言的特殊语法,和 val.(int)什么的不一样
    stevenbipt
        3
    stevenbipt  
       Jun 22, 2020   ❤️ 1
    .(type)会返回 interface{}的类型,然后使用 switch 匹配类型的 case,这里的 case 甚至可以是接口类型,算是 go 的一个专用语法了
    tidyoux
        4
    tidyoux  
       Jun 22, 2020
    简单说,可以认为 i.(type) 返回了 i 的值和类型,switch 比较用的是类型,值是方便程序员用的。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6198 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 02:22 · PVG 10:22 · LAX 19:22 · JFK 22:22
    ♥ Do have faith in what you're doing.