dpzlz08480 2013-05-20 19:47
浏览 75
已采纳

进行编程-使用指针绕过访问权限

Let's say I have the following hierarchy for my project:

fragment/fragment.go
main.go

And in the fragment.go I have the following code, with one getter and no setter:

package fragment

type Fragment struct {
    number int64   // private variable - lower case
}

func (f *Fragment) GetNumber() *int64 {
    return &f.number
}

And in the main.go I create a Fragment and try to change Fragment.number without a setter:

package main

import (
    "fmt"
    "myproject/fragment"
)

func main() {
    f := new(fragment.Fragment)

    fmt.Println(*f.GetNumber()) // prints 0

    //f.number = 8 // error - number is private

    p := f.GetNumber()
    *p = 4                      // works. Now f.number is 4
    fmt.Println(*f.GetNumber()) // prints 4
}

So by using the pointer, I changed the private variable outside of the fragment package. I understand that in for example C, pointers help to avoid copying large struct/arrays and they are supposed to enable you to change whatever they're pointing to. But I don't quite understand how they are supposed to work with private variables.

So my questions are:

  1. Shouldn't the private variables stay private, no matter how they are accessed?
  2. How is this compared to other languages such as C++/Java? Is it the case there too, that private variables can be changed using pointers outside of the class?

My Background: I know a bit C/C++, rather fluent in Python and new to Go. I learn programming as a hobby so don't know much about technical things happening behind the scenes.

  • 写回答

1条回答 默认 最新

  • du22399 2013-05-20 19:58
    关注

    You're not bypassing any access privilegies. If you acquire a *T from any imported package then you can always mutate *T, ie. the pointee at whole, as in an assignment. The imported package designer controls what you can get from the package, so the access control is not yours.

    The restriction to what's said above is for structured types (structs), where the previous still holds, but the finer granularity of access control to a particular field is controlled by the field's name case even when referred to by a pointer to the whole structure. The field name must be uppercase to be visible outside its package.

    Wrt C++: I believe you can achieve the same with one of the dozens C++ pointer types. Not sure which one, though.

    Wrt Java: No, Java has no pointers. Not really comparable to pointers in Go (C, C++, ...).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。