go 语言学习九 - String()

Posted scala

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go 语言学习九 - String()相关的知识,希望对你有一定的参考价值。

package main

import "fmt"

func main() {
/*
	一个类型如果定义了指针接收者的String方法: func (p *Type) String() string {}
	 打印这个类型的指针时会调用,
	 打印这个类型的值时不会调用。
 */
	var x Xint = 123
	fmt.Println(x) // 123
	fmt.Println(&x) // can not print Xint point.

/*
	一个类型如果定义了值接收者的String方法: func (p Type) String() string {}
	打印这个类型的变量的值和指针都会调用
 */ 
	
	var y Yint = 123
	fmt.Println(y) //can not print Yint.
	fmt.Println(&y) //can not print Yint.
	
}

type Xint int

func (x *Xint) String() string {

	return "can not print Xint point."
}

type Yint int

func (x Yint) String() string {
	
	return "can not print Yint."
}

以上是关于go 语言学习九 - String()的主要内容,如果未能解决你的问题,请参考以下文章