golang如何修改struct的未导出的域

栏目: Go · 发布时间: 7年前

内容简介:golang如何修改struct的未导出的域这里例子说明如何使用reflect包来访问修改未导出的域。假设定义了package:

golang如何修改struct的未导出的域

这里例子说明如何使用reflect包来访问修改未导出的域。

假设定义了package:

package mypackage

type MyStruct struct {
    ii  int
    ss  string
    aa  []int
}

func NewMyStruct(i int, s string, a []int) *MyStruct {
    return & MyStruct {
        ii : i,
        ss : s,
        aa : a,
    }
}

在main里面调用:

package main

import (
    "reflect"
    "unsafe"
    "fmt"

    "mypackage"
)


func main() {
    foo := mypackage.NewMyStruct(11, "AA", []int{1,2,3})
    fmt.Printf("foo1=[%v]\n", foo)

    rs  := reflect.Indirect(reflect.ValueOf(foo))

    // change field ii
    rf  := rs.FieldByName("ii")
    ptr := unsafe.Pointer(rf.UnsafeAddr())
    *(*int)(ptr) = 22

    // change field ss
    rf  = rs.FieldByName("ss")
    ptr = unsafe.Pointer(rf.UnsafeAddr())
    *(*string)(ptr) = "BB"

    // change field aa
    rf  = rs.FieldByName("aa")
    ptr = unsafe.Pointer(rf.UnsafeAddr())
    *(*[]int)(ptr) = []int{4, 5, 6}

    fmt.Printf("foo2=[%v]\n", foo)
}

运行结果:

foo1=[&{11 AA [1 2 3]}]
foo2=[&{22 BB [4 5 6]}]

我们看到MyStruct的三个域都被改过了。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Hit Refresh

Hit Refresh

Satya Nadella、Greg Shaw / HarperBusiness / 2017-9-26 / USD 20.37

Hit Refresh is about individual change, about the transformation happening inside of Microsoft and the technology that will soon impact all of our lives—the arrival of the most exciting and disruptive......一起来看看 《Hit Refresh》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具