varのメモリアドレスを直接印刷するだけで、インターフェイスから同じ動作をさせようとするとメモリアドレスが表示されないのはなぜですか?Golang:メモリアドレスを出力するインタフェースfunc
package main
import "fmt"
type address struct {
a int
}
type this interface {
memory()
}
func (ad address) memory() {
fmt.Println("a - ", ad)
fmt.Println("a's memory address --> ", &ad)
}
func main() {
ad := 43
fmt.Println("a - ", ad)
fmt.Println("a's memory address --> ", &ad)
//code init in here
thisAddress := address{
a: 42,
}
// not sure why this doesnt return memory address as well?
var i this
i = thisAddress
i.memory()
}
https://play.golang.org/p/Ko8sEVfehv
ちょうどエラーを修正した後、これを追加したい、それが今、期待通りに機能します。メモリポインタ
package main
import "fmt"
type address struct {
a int
}
type this interface {
memory() *int
}
func (ad address) memory() *int {
/*reflect.ValueOf(&ad).Pointer() research laws of reflection */
var b = &ad.a
return b
}
func main() {
thisAddress := address{
a: 42,
}
thatAddress := address{
a: 43,
}
var i this
i = thisAddress
a := i.memory()
fmt.Println("I am retruned", a)
fmt.Println("I am retruned", *a)
i = thatAddress
c := i.memory()
fmt.Println("I am retruned", c)
fmt.Println("I am retruned", *c)
}
https://play.golang.org/p/BnB14-yX8B
この場合、 'reflect'パッケージを使用してください。 'reflect.ValueOf(&ad).Pointer()'は 'uintptr'として&ad(ポインタ値)を返します。 –
ありがとう、ちょうど反射を参照して今反射の法律を読んでいる。 –