首页 > 解决方案 > 如何在更改字符串方法的类型之前打印类型

问题描述

在更改类型的 String 方法中具有 String 方法的字符串方法之前,我无法在类型上调用 Print:

type book struct{
  id int
  r relateF
  //Or can be delare as r relateF
}
type relateF struct{
  handle int
  grade float64
  name string
}
func(b book) String() string{
  fmt.Println(b)//<=I want to print it before change String method
  return fmt.Sprintf(b.r.name)
}
func main(){
  b1:= book{456,relateF{5,48.2,"History of the world"}}
  fmt.Println(b1)
}

它做了一个循环

标签: go

解决方案


一种方法是声明一个具有完全相同结构 a 的新临时类型,book然后将book实例转换为这种新类型。

func (b book) String() string {
    type temp book       // same structure but no methods
    fmt.Println(temp(b)) // convert book to temp
    return fmt.Sprintf(b.r.name)
}

https://play.golang.com/p/3ebFhptJLxj


推荐阅读