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

go 下怎么实现类似__weak 功能?

  •  
  •   afxcn ·
    afxcn · 29 天前 · 1897 次点击

    stm32 开发中经常能见到这样的函数:

    _weak void HAL_UART_AbortReceiveCpltCallback(UART_HandleTypeDef *huart)
    {
      /* Prevent unused argument(s) compilation warning */
      UNUSED(huart);
    
      /* NOTE : This function should not be modified, when the callback is needed,
                the HAL_UART_AbortReceiveCpltCallback can be implemented in the user file.
       */
    }
    

    我只需要随便在一个地方重写这个函数,它最终调用的就是我的函数:

    void HAL_UART_AbortReceiveCpltCallback(UART_HandleTypeDef *huart)
    {
      //做一些爱做的事情
    }
    

    如果我只想定义些简单的函数,用户可以在自己喜欢的地方重写它,go 中怎么实现类似的功能,或者 go 中有更好的实现?

    6 条回复    2024-09-10 08:17:53 +08:00
    k9982874
        1
    k9982874  
       29 天前 via Android
    没有,go 没有函数重载,用 interface
    pagxir
        2
    pagxir  
       29 天前 via Android   ❤️ 3
    这个是连接器跟装载器的特性,如果会写 ld 脚本,理论可以实现
    kumoocat
        3
    kumoocat  
       29 天前
    povsister
        4
    povsister  
       29 天前
    go 不需要这种花里胡哨的写法。
    binary 分发:cgo 走动态链接
    源代码分发:走 build constraint ,你提供一个基础版本的实现,让用户自己写个源代码函数实现,然后 build flag 就可以了
    Maboroshii
        5
    Maboroshii  
       29 天前 via Android
    interface 或者传一个函数指针也能实现相同的功能吧,门槛也低
    afxcn
        6
    afxcn  
    OP
       14 天前
    好像用 go 实现这个没什么意义,但这思路用在代码生成上倒是很不错。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5098 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 07:24 · PVG 15:24 · LAX 00:24 · JFK 03:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.