Go1.7+中的BCE(Bounds Check Elimina

作者: Zeal_8421 | 来源:发表于2017-09-21 14:53 被阅读74次

    自go1.7+,我们可以在编译时开启对有潜在slice越界访问风险的语句进行提示。

    原文地址(需梯子):

    http://www.tapirgames.com/blog/go-1.7-bce

    本文引用了原文中的一小段示例,只是简单的讲解一下BCE如何使用,更深入的使用方法请各位参考原文。

    package main
    
    func f1(s []int) {
        _ = s[0] // line 5: bounds check 
        _ = s[1] // line 6: bounds check 
        _ = s[2] // line 7: bounds check 
    }
    

    此处代码并未对slice的使用进行边界校验,容易发生危险,因为 s []int 尺寸未知。

    go build -gcflags="-d=ssa/check_bce/debug=1" main.go
    
    # command-line-arguments
    ./main.go:14:5: Found IsInBounds
    ./main.go:15:6: Found IsInBounds
    ./main.go:16:7: Found IsInBounds
    

    当我们把上面的代码修改为:

    func f1(s []int) {
    
        if len(s) < 3 {
            return
        }
    
        _ = s[0] // line 5: bounds check
        _ = s[1] // line 6: bounds check
        _ = s[2] // line 7: bounds check
    }
    

    再执行刚才的命令,就不会再提示有越界的可能了

    相关文章

      网友评论

        本文标题:Go1.7+中的BCE(Bounds Check Elimina

        本文链接:https://www.haomeiwen.com/subject/mjnzsxtx.html