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?

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

报告相同问题?

悬赏问题

  • ¥35 VBA-JSON中文乱码报错
  • ¥50 dac adc的检定规程
  • ¥20 MIT控制器能控制不稳定系统吗
  • ¥15 公司代码X对业务伙伴X无效,处理方法?
  • ¥15 微信内链接跳转到浏览器打开怎么实现
  • ¥15 三角波可以直接加施密特电路整形到矩形波吗实物
  • ¥15 html,php,在使用html请求php文件时发生了错误,无法请求到php文件读取数据库并用javascript进行数据显示,刷新
  • ¥15 touchsocket udp组播
  • ¥20 MAC怎么安装Silverlight 插件?以及安装了怎么启用
  • ¥15 gis系统开发出现命名空间“ESRI.ArcGIS”中不存在类型或命名空间名“Analyst3D”报错