pointers - 指针问题

标签 pointers go append slice

TL;DR 不知何故,我将一个指针 append 到列表而不是对象的 for 循环中的对象,所以最后整个 slice 多次由同一个对象组成。我只是不知道如何解决这个问题。

漫漫长路

我仍然很难在 go 中找出指针。我昨天发布了一个问题并得到了一些帮助,但现在我在同一段代码中遇到了一个稍微不同的问题。

我正在使用 gocqlcqlr go 包来尝试为我的 Cassandra 查询编写一个小型对象映射器。从本质上讲,我遇到的问题是我将似乎是指向对象的指针,而不是 obj 的新实例 append 到数组中。我该如何解决?我尝试在 value 前面添加 &* 但这似乎不起作用。我该如何解决这些问题?根据他们的文档,绑定(bind)函数需要一个 &

代码

type Query struct {
    query       string
    values      interface{}
    attempts    int
    maxAttempts int
    structType  reflect.Type
}

func (query Query) RetryingQuery() (results []interface{}) {
    var q *gocql.Query
    if query.values != nil {
        q = c.Session.Query(query.query, query.values)
    } else {
        q = c.Session.Query(query.query)
    }

    bindQuery := cqlr.BindQuery(q)
    value := reflect.New(query.structType).Interface()
    for bindQuery.Scan(value) {
        fmt.Println(value)
        results = append(results, value)
    }
    return
}

文档要求 var value type 然后在绑定(bind)中你将传递 &value。我引用了下面的文档。

var t Tweet
var s []Tweet
for b.Scan(&t) {
    // Application specific code goes here
    append(s, t)
}

问题是我不能直接去 var value query.structType 定义它的类型,然后将它的引用传递给 bindQuery.Scan()

打印什么

&{result1 x86_64 24 3.2.0-74-generic Linux}
&{result2 x86_64 24 3.19.0-25-generic Linux}
&{result3 x86_64 4 3.13.0-48-generic Linux}
&{result4 x86_64 2 3.13.0-62-generic Linux}
&{result5 x86_64 4 3.13.0-48-generic Linux}

slice 里有什么

剧透result5 一遍又一遍地重复。我知道我只是将指向同一对象的指针 append 到列表中,并且每次循环迭代都会更改该对象,并将 slice 中的所有结果更改为该新对象。我只是不知道如何修复它。

[{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"},{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"},{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"},{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"},{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"}]

最佳答案

好吧,我至少可以告诉你你在做什么。 bindQuery 接受一个指针。它会更改地址中存储的值。

你实际上在做的是:

package main

import "fmt"

func main() {
    var q int
    myInts := make([]*int, 0, 5)
    for i := 0; i < 5; i++ {
        q = i
        fmt.Printf("%d ", q)
        myInts = append(myInts, &q)
    }
    fmt.Printf("\n")
    for _, value := range myInts {
        fmt.Printf("%d ", *value)
    }
    fmt.Printf("\n")
    fmt.Println(myInts)
}

正如您可能猜到的那样,它给了您:

0 1 2 3 4 
4 4 4 4 4 
[0x104382e0 0x104382e0 0x104382e0 0x104382e0 0x104382e0]

reflect 会让事情变得更加困惑。您可以将类型作为接口(interface)获取,但仅此而已(除非您想使用 unsafe)。简单来说,一个接口(interface)包含一个指向下面原始类型(以及其他一些东西)的指针。所以在你的函数中你传递了一个指针(和其他一些东西)。然后你追加指针。获得具体的类型并切换您的界面可能会很好。我假设你知道它可能是什么类型。在这种情况下,您必须遵循以下原则:

package main

import (
    "fmt"
    "reflect"
)

type foo struct {
    fooval string
}

type bar struct {
    barval string
}

func main() {
    f1 := foo{"hi"}
    f2 := &foo{"hi"}
    b1 := bar{"bye"}
    b2 := &bar{"bye"}

    doSomething(f1)
    doSomething(f2)
    doSomething(b1)
    doSomething(b2)

}

func doSomething(i interface{}) {
    n := reflect.TypeOf(i)
    // get a new one
    newn := reflect.New(n).Interface()
    // find out what we got and handle each case
    switch t := newn.(type) {
    case **foo:
        *t = &foo{"hi!"}
        fmt.Printf("It was a **foo, here is the address %p and here is the value %v\n", *t, **t)
    case **bar:
        *t = &bar{"bye :("}
        fmt.Printf("It was a **bar, here is the address %p and here is the value %v\n", *t, **t)
    case *foo:
        t = &foo{"hey!"}
        fmt.Printf("It was a *foo, here is the address %p and here is the value %v\n", t, *t)
    case *bar:
        t = &bar{"ahh!"}
        fmt.Printf("It was a *bar, here is the address %p and here is the value %v\n", t, *t)
    default:
        panic("AHHHH")
    }
}

您也可以在循环内继续调用 value = reflect.New(query.structType).Interface(),这样每次都会为您提供新的接口(interface)。每次 append 后重新分配值。最后一次通过循环会多做一个..

关于pointers - 指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33786353/

相关文章:

c - 为什么 char[512] 的地址等于 char[512]

不能声明两个字符指针

go - 当客户端重新连接到我的 TCP 服务器时,内存不断增加

powershell - RedirectStandardError $logFile 并 append ?

python - 根据每个单独数据帧的行索引(编号)连接/加入/合并多个数据帧

c++ - 返回指向引用的指针

C# 奇怪的方法调用使用指针?

io - 读取()函数

go - 如何使用golang查询将数据流传输到Cassandra

swift - 您可以将路径相互组合(追加)吗?