fmt: stack overflow

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)
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值