douzhiji2020 2018-11-21 00:02
浏览 83

为什么我的Golang定义方法没有在String()时隐式实现

In https://tour.golang.org/methods/11

It states Under the hood, interface values can be thought of as a tuple of a value and a concrete type

I define M as follows

script1

package main

import (
    "fmt"
)

type I interface {
    M() string
}
type T struct {
    S string
    w string
}
func (t T) M() string {
    return "dddd"
}
func main() {
    var i I
    i = T{"Hello","eeee"}  
    fmt.Printf("(%v, %T)", i, i)    
    fmt.Println(i)
}

This prints out ({Hello eee}, main.T){Hello eee} interface i has vaule {Hello eee} and type main.T

script2:

package main

import (
    "fmt"
)

type I interface {
    M() string
}
type T struct {
    S string
    w string
}
func (t T) M() string {
    return "dddd"
}
func (t T) String() string {
    return "ccccc"
}
func main() {
    var i I
    i = T{"Hello","eeee"}
    fmt.Printf("(%v, %T)", i, i) 
    fmt.Println(i)
}

This prints out (ccccc, main.T)ccccc.

interface i has vaule ccccc and type main.T

Seems when i add String() as Stringer defined by the fmt package in script2. The String() is implemented implicitily,not sure why?

I thought in script2 i would have value "{Hello eee}" and type main.T

  • 写回答

2条回答 默认 最新

  • duankui6150 2018-11-21 01:34
    关注

    You should call fmt.Println(i.M()) ?
    Why you want fmt call a function while its'n exist?

    A Stringer is a type that can describe itself as a string. The fmt package (and many others) look for this interface to print values

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值