The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
yujianwjj

go 编译检查的一个问题

  •  
  •   yujianwjj · Mar 11, 2025 · 2081 views
    This topic created in 440 days ago, the information mentioned may be changed or developed.
    package cluster
    
    import "fmt"
    
    func A() error {
    	return fmt.Errorf("a", 1)  // 这行代码应该报错
    }
    
    package cluster
    
    import (
    	"testing"
    )
    
    func TestT(t *testing.T) {
    	A()
    }
    

    运行 TestT 函数会报错,fmt.Errorf call has arguments but no formatting directives 。

    package clusterrolebinding
    
    import (
    	"xx/pkg/controller/cluster"
    	"testing"
    )
    
    func TestT(t *testing.T) {
    	cluster.A()
    }
    

    但是在另外一个包里面运行 TestT 函数就不报错了,正常运行。

    3 replies    2025-03-11 15:27:28 +08:00
    kkhaike
        1
    kkhaike  
       Mar 11, 2025
    golang 编译器在构建 test 会检查 fmt 参数,还包括你的 fmt 里的格式化符对不对,但是普通构建没有这个功能,我也觉得这个功能挺好的。。。现在只能靠 golang-lint
    v1
        2
    v1  
       Mar 11, 2025
    因为你用 fmt.Errorf 但是没有格式说明符(%v\%s\%d 等),包内检查,包外不检查
    zzhirong
        3
    zzhirong  
       Mar 11, 2025   ❤️ 1
    @kkhaike “As part of building a test binary, go test runs go vet on the package and its test source files to identify significant problems. ” 以上这段话摘自`go test`文档。`go test`会在编译测试代码之前,运行`go vet`,`go build `则不会。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6069 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 06:16 · PVG 14:16 · LAX 23:16 · JFK 02:16
    ♥ Do have faith in what you're doing.