duanhe2027 2019-01-22 11:53
浏览 12
已采纳

为什么不按名称调用此String()方法

Consider the following code. The first function is a receiver method for type MessageStr. Why fmt.Println(msgstr) executes the first method without calling the method as fmt.Println(msgstr.String()). Also why fmt.Println(msgint32) doesn't execute the second method.

package main

import (
    "fmt"
)

type MessageStr string
type MessageInt32 int32

func (msgs MessageStr) String() string {
    return string("<<" + msgs + ">>")
}

func (msgi MessageInt32) Int32() int32 {
    return int32(msgi * 2)
}

func main() {

    msgstr := MessageStr("Mastering Go")
    // why this outputs <<Mastering Go>>
    // without calling the String() method
    fmt.Println(msgstr)


    msgint32 := MessageInt32(11)
    // why this doesn't output 11*2 = 22
    fmt.Println(msgint32)

    fmt.Println(msgint32.Int32())

}
  • 写回答

1条回答 默认 最新

  • dpbdl44228 2019-01-22 13:31
    关注

    When you call fmt.Println, it expects an object that implements the Stringer interface. It's documented as follows:

    If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any)

    The fmt package also declares the Stringer interface:

    type Stringer interface {
        String() string
    }
    

    Such objects must have a String() method that takes no arguments and returns a string. fmt.Println then invokes the String method. This lets us define for custom types how they're going to be printed out. For example:

    package main
    
    import "fmt"
    
    type Person struct {
        name string
        age  int
    }
    
    func (p Person) String() string {
        return fmt.Sprintf("%s<%d>", p.name, p.age)
    }
    
    func main() {
        p := Person{name: "Joe", age: 39}
        fmt.Println(p)
    }
    

    Will print out:

    Joe<39>
    

    Because we've customized the way Person objects are turned into strings. More details:


    If you're interested in the mechanics of how this actually happens in the fmt package, take a look at the handleMethods method in src/fmt/print.go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)