What exactly does .(data_type) method called/do?

后端 未结 2 1495
孤街浪徒
孤街浪徒 2020-12-04 04:18

I came a cross a piece of code that used .(string) method. Not knowing what this is called I had difficulties searching for it.

Here is my try to unders

2条回答
  •  有刺的猬
    2020-12-04 04:25

    The previous answer is correct. But I submit this as more like what happens in practice. The .(type) syntax is usually used with type names in the cases of a switch. In this example, I (integer expr), B (bool expr), and Bop (binary op) are type names.

    func commute (e Expr) (r Expr, d bool) {
        switch exp:= e.(type) {
            case I: r,d = exp,false
            case B: r,d = exp,false
            case Bop: r,d = Bop{exp.op, exp.right, exp.left},true
            default: r,d = e,false
        }
        return
    }
    

    This isn't unsafe like a C cast, because inside the case statement you are guaranteed to have the matching type. I see this quite a bit when reading a channel, where the type of the channel is an interface that all the cases implement.

提交回复
热议问题