V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
yujianwjj
V2EX  ›  Go 编程语言

go 编译检查的一个问题

  •  
  •   yujianwjj · 97 天前 · 1411 次点击
    这是一个创建于 97 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2025-03-11 15:27:28 +08:00
    kkhaike
        1
    kkhaike  
       97 天前
    golang 编译器在构建 test 会检查 fmt 参数,还包括你的 fmt 里的格式化符对不对,但是普通构建没有这个功能,我也觉得这个功能挺好的。。。现在只能靠 golang-lint
    kk2syc
        2
    kk2syc  
       97 天前
    因为你用 fmt.Errorf 但是没有格式说明符(%v\%s\%d 等),包内检查,包外不检查
    zzhirong
        3
    zzhirong  
       96 天前   ❤️ 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 `则不会。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3462 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 04:23 · PVG 12:23 · LAX 21:23 · JFK 00:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.