亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

掃描不工作

掃描不工作

Go
素胚勾勒不出你 2021-12-07 18:44:11
我的掃描未更新其目標變量。我有點讓它與:ValueName := reflect.New(reflect.ValueOf(value).Elem().Type())但我不認為它以我想要的方式工作。func (self LightweightQuery) Execute(incrementedValue interface{}) {    existingObj := reflect.New(reflect.ValueOf(incrementedValue).Elem().Type())    if session, err := connection.GetRandomSession(); err != nil {        panic(err)    } else {        // buildSelect just generates a select query, I have test the query and it comes back with results.        query := session.Query(self.buildSelect(incrementedValue))        bindQuery := cqlr.BindQuery(query)        logger.Error("Existing obj ", existingObj)        for bindQuery.Scan(&existingObj) {            logger.Error("Existing obj ", existingObj)            ....        }   }}兩條日志消息完全相同Existing obj &{ 0  0  0 0 0 0 0 0 0 0 0 0}(空格是字符串字段。)這是因為大量使用反射來生成新對象嗎?在他們的文檔中,它說我應該var ValueName type用來定義我的目的地,但我似乎無法通過反射來做到這一點。我意識到這可能很愚蠢,但即使只是指出我進一步調試的方向也會很棒。我的圍棋技巧非常缺乏!
查看完整描述

1 回答

?
侃侃無極

TA貢獻2051條經驗 獲得超10個贊

你到底想要什么?您想更新傳遞給的變量Execute()嗎?


如果是這樣,您必須將指針傳遞給Execute(). 然后你只需要傳遞reflect.ValueOf(incrementedValue).Interface()給Scan(). 這是有效的,因為reflect.ValueOf(incrementedValue)是一個reflect.Value持有一個interface{}(您的參數的類型),它持有一個指針(您傳遞給的指針Execute()),Value.Interface()并將返回一個interface{}持有指針的類型的值,您必須傳遞的確切內容Scan()。


請參閱此示例(使用fmt.Sscanf(),但概念相同):


func main() {

    i := 0

    Execute(&i)

    fmt.Println(i)

}


func Execute(i interface{}) {

    fmt.Sscanf("1", "%d", reflect.ValueOf(i).Interface())

}

它將1從打印main(),因為該值1設置在 內Execute()。


如果您不想更新傳遞給 的變量Execute(),只需創建一個具有相同類型的新值,因為您使用的reflect.New()是返回Value指針的 ,您必須傳遞existingObj.Interface()返回一個interface{}持有指針的指針,您想要的東西傳遞給Scan(). (你所做的是你傳遞了一個指向 a 的指針reflect.Value,Scan()這不是所Scan()期望的。)


演示fmt.Sscanf():


func main() {

    i := 0

    Execute2(&i)

}


func Execute2(i interface{}) {

    o := reflect.New(reflect.ValueOf(i).Elem().Type())

    fmt.Sscanf("2", "%d", o.Interface())

    fmt.Println(o.Elem().Interface())

}

這將打印2.


的另一個變體Execute2()是,如果您直接調用Interface()由 返回的值reflect.New():


func Execute3(i interface{}) {

    o := reflect.New(reflect.ValueOf(i).Elem().Type()).Interface()

    fmt.Sscanf("3", "%d", o)

    fmt.Println(*(o.(*int))) // type assertion to extract pointer for printing purposes

}

這Execute3()將按3預期打印。


嘗試Go Playground上的所有示例。


查看完整回答
反對 回復 2021-12-07
  • 1 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號