美文网首页
go fmt 引起的 stack overflow

go fmt 引起的 stack overflow

作者: 七秒钟回忆待续 | 来源:发表于2019-07-15 14:23 被阅读0次

在 GO 里实现 String 方法会格式化输出。例如:

package main

import (
    "fmt"
)

type People struct {
    Name string
    Age  int
    Sex  string
}

func (p *People) String() string {
    return fmt.Sprintf("people info: %+v", p)
}

func main() {
    p := &People{Name: "Lucy", Age: 18, Sex: "M"}
    fmt.Println(p)
}

预期的结果是:people info: &{Name:Lucy Age:18 Sex:M}
实际的结果是:

runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
runtime stack:

在 go 的源码里:src/fmt/print.go::StringerStringer 接口有 String 方法,People struct 也有 String 方法,间接实现了 Stringer 接口,因此出现了 stack overflow 的错误,递归了。

解决办法:

  • String 方法改为 ToString
  • People.String 方法里传递属性,即把 fmt.Sprintf("people info: %+v", p) 改为 fmt.Sprintf("people info: Name:%s, Age:%d, Sex:%s", p.Name, p.Age, p.Sex)

参考文章: golang fmt递归引起stack overflow异常

相关文章

网友评论

      本文标题:go fmt 引起的 stack overflow

      本文链接:https://www.haomeiwen.com/subject/ftxnkctx.html