package main
import (
"fmt"
)
type Str string
func (s Str) String() string {
return fmt.Sprintf("Str: %s", s)
}
func main() {
var s Str = "hi"
fmt.Println(s)
}
RunCode:
runtime: goroutine stack exceeds 250000000-byte limit
fatal error: stack overflow
runtime stack:
runtime.throw(0x4e33b0, 0xe)
D:/go/src/runtime/panic.go:530 +0x7f
runtime.newstack()
D:/go/src/runtime/stack.go:940 +0x9a7
runtime.morestack()
D:/go/src/runtime/asm_386.s:382 +0x6f
goroutine 1 [stack growth]:
runtime.heapBitsSetType(0x1270c200, 0x8, 0x8, 0x4c1860)
D:/go/src/runtime/mbitmap.go:679 fp=0x18b10a7c sp=0x18b10a78
.....
原因:
You are implementing Str.String
in terms of itself. return fmt.Sprintf("Str: %s", s)
will call s.String(), resulting in infinite recursion. Convert s to string first.
This is working as intended, you are using the %s verb to call Str's String method, which uses fmt.Sprint to call Str's String method, and so on.
修改后代码:
package main
import (
"fmt"
)
type Str string
func (s Str) String() string {
return fmt.Sprintf("Str: %s", string(s))
}
func main() {
var s Str = "hi"
fmt.Println(s)
}