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

求助:前辈们可以分享一下你们觉得比较良好写 golang 代码的习惯吗

  •  
  •   lllsj · 24 天前 · 1941 次点击
    各位前辈你们好,我最近刚入职一个公司实习,公司这边用的都是 Golang ,我也是刚上手没多久,请问各位可以分享一下平时写 go 比较好的习惯吗,我想学习学习,不胜感激
    16 条回复    2024-10-18 10:55:05 +08:00
    securityCoding
        1
    securityCoding  
       24 天前
    kiss
    GeekGao
        2
    GeekGao  
       24 天前
    老生常谈,SOLID 原则
    konakona
        3
    konakona  
       24 天前
    我推荐去了解 Go 语言研发作者团队的构想,你就会发现他们压根没有你的这些考虑,一切从简出发。
    poltao
        4
    poltao  
       24 天前
    不用考虑太多,公司代码跟着存量的代码保持已有代码风格就可以了,重要的是要多理解业务,便于以后出去面试吹牛。最后如果未来面试也是 golang 方向的话可以多看看 golang 的八股文,了解下异步编程和 GMP 模型,有时间理解下 RPC 框架,看看 golang 常用的 etcd, mq 等微服务组件足矣。
    povsister
        5
    povsister  
       24 天前 via iPhone
    go 的风格就是没有统一风格。跟项目风格,否则你水平比项目高或者低写的都只会很憋屈。
    lllsj
        6
    lllsj  
    OP
       24 天前
    @poltao #4 嗯嗯,好的感谢
    lllsj
        7
    lllsj  
    OP
       24 天前
    @povsister #5 确实,我感觉我接手的代码风格就很乱,跟我同批的实习生他们组的代码写的就很规范
    dododada
        8
    dododada  
       23 天前
    不要用魔法变量, 能跑就行
    uds9u32br
        9
    uds9u32br  
       23 天前
    不要有什么设计是最好的,除非必要,否则应该禁用设计模式。
    试着模仿标准库的代码风格吧。
    chouvel
        10
    chouvel  
       23 天前
    @poltao 很认同。感觉可以思维也可以应用在其他工作上。
    lveye
        12
    lveye  
       23 天前
    比如一些容易踩坑的点:

    timer := time.NewTimer(time.Minute)
    defer timer.Stop()

    ----
    for i := range array {
    i := i
    go func() {
    fmt.Println(i)
    }()
    }

    ----
    resp, _ := http.Post(urlStr, "application/x-www-form-urlencoded", body)
    defer func() {
    _ = resp.Body.Close()
    }

    ----
    ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    defer cancel()

    go func(i int)
    // do something
    select {
    case <- ctx.Done():
    fmt.Println(i)
    }
    }(i)
    Biem
        13
    Biem  
       22 天前
    go 的风格就是 go ,just go ,let it go ,越简单越好,只要不碰 unsafe ,能跑起来就是好代码。然后节省下来过度设计和思考的时间去体验生活。
    windcode
        14
    windcode  
       9 天前   ❤️ 1
    可以阅读一些开源项目的「开发者指南」部分,已经帮你总结好了优秀的编码规约:
    - 代码规约: https://www.kusionstack.io/zh/karpor/developer-guide/conventions/code-conventions
    - 测试规约: https://www.kusionstack.io/zh/karpor/developer-guide/conventions/test-conventions
    - Commit 规约: https://www.kusionstack.io/zh/karpor/developer-guide/conventions/commit-conventions
    lllsj
        15
    lllsj  
    OP
       9 天前
    @windcode #14 好的,感谢您
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1260 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:01 · PVG 02:01 · LAX 11:01 · JFK 14:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.