doushui5587 2016-11-20 09:35
浏览 50
已采纳

为什么在golang的以下代码示例中switch匹配其他类型

Link: https://play.golang.org/p/69I8PAuoAV

Extract:

package main

import "fmt"

type Stringer interface {
    String() string
}

type fakeString struct {
    content string
}

// function used to implement the Stringer interface
func (s *fakeString) String() string {
    return s.content
}

func printString(value interface{}) {
    switch str := value.(type) {
    case string:
        fmt.Println(str)
    case Stringer:
        fmt.Println(str.String())
    }
}

func main() {
    s := &fakeString{"Ceci n'est pas un string"}
    printString(s)
    printString("Hello, Gophers")

}

The printString(s) function call when reaching case matches the case Stringer part. s is of type *fakeString not Stringer. Why does it match Stringer.

I did a fmt.Println(reflect.TypeOf(str)) and it confirmed the type as *main.fakeString

  • 写回答

2条回答 默认 最新

  • douliu8327 2016-11-21 03:44
    关注

    This is interface satisfaction in golang.

    There are two kinds of type in golang: interface type and concrete type.

    • concrete type works exactly as you expected in switch: the variable is an instance of the given type
    • interface type on the other hand works differently, it checks if the variable satisfies the interface.

    Hum, safisfies? How does it work?

    A (concrete) type satisfies an interface if it possesses all the methods the interface requires.

    -- the golang programming language

    In the case, Stringer is an interface, declaring only one method: String() string. And fakeString satisfies it by having its own String() string method.

    Two things to note however:

    1. concrete type can have many other methods, it still satisfies the interface if it possesses all methods declared in interface
    2. the methods order does not matter, all that matters is the set of methods.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失