2012-09-18 24 views
6

kod aşağıdakilere sahip arayüz için herhangi bir değer ayarlamak için:Nasıl {}

package main 

import (
    "fmt" 
) 

type Point struct { 
    x,y int 
} 

func decode(value interface{}) { 
    fmt.Println(value) // -> &{0,0} 

    // This is simplified example, instead of value of Point type, there 
    // can be value of any type. 
    value = &Point{10,10} 
} 

func main() { 
    var p = new(Point) 
    decode(p) 

    fmt.Printf("x=%d, y=%d", p.x, p.y) // -> x=0, y=0, expected x=10, y=10 
} 

Ben decode işleve iletilen değerin, her türden değeri ayarlamak istiyorum. Go'da mümkün mü, yoksa bir şeyi yanlış anladım mı?

http://play.golang.org/p/AjZHW54vEa

+1

Git pass-değeriyle . Yerel bir değişkene bir şey atamak asla dışarıyı etkilemez. Durumu paylaşmak için işaret ettiği şeyi değiştirmek için bir referans türünü (işaretçi gibi) kullanabilirsiniz; ama sonra işaret ettiği şeylere bir şey atamanız için doğru tipte bir işaretçiye ihtiyaç duyacaktır. – newacct

cevap

5

Generically, sadece using reflection:

package main 

import (
    "fmt" 
    "reflect" 
) 

type Point struct { 
    x, y int 
} 

func decode(value interface{}) { 
    v := reflect.ValueOf(value) 
    for v.Kind() == reflect.Ptr { 
     v = v.Elem() 
    } 
    n := reflect.ValueOf(Point{10, 10}) 
    v.Set(n) 
} 

func main() { 
    var p = new(Point) 
    decode(p) 
    fmt.Printf("x=%d, y=%d", p.x, p.y) 
} 
+0

İhtiyacım olan bu, teşekkür ederim! –

1

ben kesin hedefi emin değilim. Eğer valuePoint bir işaretçi olduğunu assert istiyoruz ve bunu değiştirirseniz

, bunu yapabilirsiniz:

func decode(value interface{}) { 
    p := value.(*Point) 
    p.x=10 
    p.y=10 
} 
+1

ayrıca varolan bir noktayı p: = değeriyle değiştirebilirsiniz (* Nokta); * p = Nokta {20, 20} ' – newacct

+0

@newacct Hum ... tamamen haklısınız ... Cevabımı temizledim. Ama hala OP'in gerçek niyeti olanı almadığım için, cevabın tamamını birkaç gün içinde kaldırabilirim. –