zoukankan      html  css  js  c++  java
  • golang: new 返回值

    new 之后会分配内存地址,示例代码:

    package main
    
    import (
        "bytes"
        "fmt"
    )
    
    func main() {
        var buf *bytes.Buffer
        fmt.Printf("buf init: %p | val: %v
    ", buf, buf)
    
        buf = new(bytes.Buffer) // new 之后会分配内存地址
        fmt.Printf("buf after new: %p | val: %v
    ", buf, buf)
        fmt.Printf("new buf is nil: %t
    ", buf == nil)
    
        buf.Write([]byte("done!
    "))
        fmt.Printf("buf after write:%p | val: %v
    ", buf, buf)
    }
    
    // 运行结果:
    /*
    MacBook-Pro:new_retVal_aug_15 zhenxink$ go run new_ret_val.go
    buf init: 0x0 | val: <nil>
    buf after new: 0xc00005e180 | val:
    new buf is nil: false
    buf after write:0xc00005e180 | val: done!
    
    MacBook-Pro:new_retVal_aug_15 zhenxink$
    */

    空指针的 bytes.Buffer 不能直接 Write,示例代码:

    package main
    
    import (
        "bytes"
        "fmt"
    )
    
    func main() {
        var buf *bytes.Buffer
        buf.Write([]byte("done!"))
        fmt.Printf("buf val:%v
    ", buf)
    }
    
    // 运行结果:
    /*
    MacBook-Pro:new_retVal_aug_15 zhenxink$ go run nil_buffer_write.go
    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x106aec6]
    
    goroutine 1 [running]:
    bytes.(*Buffer).Write(0x0, 0xc000068f63, 0x5, 0x5, 0xc000038778, 0xc000068f78, 0x100508f)
        /usr/local/go/src/bytes/buffer.go:169 +0x26
    main.main()
        /Users/.../nil_buffer_write.go:10 +0x57
    exit status 2
    MacBook-Pro:new_retVal_aug_15 zhenxink$
    */ 

    // For some types, such as *os.File, nil is a valid receiver, but *bytes.Buffer is not among them.

    end...

  • 相关阅读:
    flask 需要下载的包
    flask知识点
    移动端网页实现(用百分比进行定位)
    js中的preventDefault
    网页重构面试笔试题
    J2EE课程设计的购物车代码(水平有限,仅供参考)
    JavaScript实现对象克隆函数clone( )的程序及分析
    WEB技术书籍推荐
    2016 Tianjin University Software Testing (lab2)
    Mac下安装npm 、node、ionic和cordova
  • 原文地址:https://www.cnblogs.com/neozheng/p/13507332.html
Copyright © 2011-2022 走看看