douxuqiao6394 2016-09-30 01:56
浏览 37
已采纳

在Go中,是否可以在不需要星号取消引用的情况下将变量分配给someArray [someIndex]?

This works:

pressure := &dataDump[845]
CurrentPressure := *pressure

But is there a way to change the first line so that pressure is an alias for dataDump[845] and so no asterisk is needed:

CurrentPressure := pressure
  • 写回答

1条回答 默认 最新

  • doukang2003 2016-09-30 07:41
    关注

    For "changing" data

    By "changing" data I mean if the dataDump array / slice changes, you want your pressure to reflect the changes.

    This is not possible in Go. What you want would require to explicitly specify the memory address where a variable is to be created / placed.

    Your best option is to use a pointer which you included in your question.

    Another alternative would be to create a function, e.g.:

    function pressure() int {
        return dataDump[845]
    }
    

    And using it:

    currentPressure := pressure()
    

    For "static" data

    If dataDump doesn't change once it's acquired, then this is not a problem. You can use a simple non-pointer variable like this:

    pressure := dataDump[845] // Not a pointer to the element but a copy of it
    

    And then:

    currentPressure := pressure
    

    But then in this case currentPressure isn't even needed, you can just use pressure (or maybe name it currentPressure in the first place).

    Using memory layout

    I don't know how you acquire your data, but in some cases it is possible to provide the Go value where you want the data to be placed / unmarshaled. Such cases may be reading the data from a file, or from a TCP connection.

    If this is you case, you may use a struct carefully planning the memory layout of the data you get, and then you may use struct fields which you can declare to be non-pointers.

    Example:

    type dataDump struct {
        _ [845]int32 // Some unused data
    
        pressure int32
    }
    

    If you can "unmarshal" your data into a value of this struct, then you can obtain the current pressure like this:

    dump := dataDump{}
    // Unmarshal into dump
    currentPressure := dump.pressure
    

    If you go down this way, be aware of the Spec: Size and alignment guarantees. Care must be taken due to implicit alignments!

    See related questions for more details about laying out memory:

    Why use arrays instead of slices?

    Why have arrays in Go?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用