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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀