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

go 源码库竟如此惊奇???!!!!

  •  
  •   rwdy2008 · 2018-05-03 23:31:16 +08:00 · 5085 次点击
    这是一个创建于 2178 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近看到 go 的源码库,比如 bytes 库

    Count()函数如下:

    func Count(s, sep []byte) int {
    	if len(sep) == 1 && cpu.X86.HasPOPCNT {
    		return countByte(s, sep[0])
    	}
    	return countGeneric(s, sep)
    }
    

    然后看了下 countByte 库写法是下面这样:

    func countByte(s []byte, c byte) int
    

    库函数为什么可以这么写呢?没有实体?不应该语法报错吗?怎么执行呢? 来位好心人解释下吧!

    13 条回复    2018-05-30 20:24:32 +08:00
    mornlight
        1
    mornlight  
       2018-05-03 23:45:14 +08:00   ❤️ 3
    不是没实现,只是没有用 Go 代码实现,有注释啊:


    https://golang.org/src/runtime/asm_amd64.s
    imcj
        2
    imcj  
       2018-05-04 00:35:23 +08:00   ❤️ 1
    如果你仔细看看各种语言实现,你会发现很多函数只有定义没有实现。这是因为实现在另外一个盒子里面。

    countByte 是由.s 文件实现,根据 google 的搜索,.s 是由 c 编译器编译。

    就好像 SYSCALL_CANCEL 由内核实现,c 代码里面是没有这个“函数”的实现的。

    go 实现了自举,但是并没有完全抛弃 c。
    Arnie97
        3
    Arnie97  
       2018-05-04 01:32:37 +08:00 via Android
    是用汇编语言实现的,*.s 是汇编的扩展名。 @imcj
    dndx
        4
    dndx  
       2018-05-04 05:14:45 +08:00   ❤️ 1
    打开看一眼就知道了,就是用汇编实现的:

    https://golang.org/src/runtime/asm_amd64.s#L2174
    jy02201949
        5
    jy02201949  
       2018-05-04 09:05:34 +08:00
    如果楼主去看 python 库源码也会得出同样的结论
    misaka19000
        6
    misaka19000  
       2018-05-04 09:21:17 +08:00
    看代码看的不仔细啊,允悲~~
    ylcc
        7
    ylcc  
       2018-05-04 09:28:06 +08:00
    那看 python 源码就会认为有一大堆没实现的了。。。
    thincamel
        8
    thincamel  
       2018-05-04 09:30:28 +08:00
    妈蛋的,学的汇编都还给先生了...
    thincamel
        9
    thincamel  
       2018-05-04 09:31:15 +08:00
    @thincamel 看了几个文件,看不懂了都快...
    icexin
        10
    icexin  
       2018-05-04 10:35:14 +08:00
    @imcj go 有自己的汇编器,`go tool asm`
    natscat
        11
    natscat  
       2018-05-04 10:57:56 +08:00
    汇编实现的 runtime 里面一堆
    reus
        12
    reus  
       2018-05-12 00:11:43 +08:00
    @imcj 胡说八道,汇编代码自然用 go 的汇编器来编译,哪里需要 C 编译器
    imcj
        13
    imcj  
       2018-05-30 20:24:32 +08:00
    @icexin 👍
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1066 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:08 · PVG 07:08 · LAX 16:08 · JFK 19:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.