不同类型的指针有什么区别?

huangapple go评论67阅读模式
英文:

What's the difference between different type of pointers?

问题

指针引用内存中的位置。据我了解,实际上所有的内存地址都具有相同的类型,与变量类型无关。

是否可以使用一个类型(var p pointer)来代替不同的指针类型(*int*string等)?

不同指针类型之间有什么区别?

package main

import "fmt"

func main() {
    i := 5
    s := "abc"

    var pi *int      // 或者 var pi pointer
    var ps *string   // 或者 var ps pointer 
    
    pi = &i
    ps = &s
     
    fmt.Printf("%p %p", pi, ps)  // 结果为 0x1040e0f8 0x1040a120
}
英文:

A pointer references a location in memory. Actually all memory addresses have the same type independently of the variable type as far as I understand.

Instead of using different pointer type (*int, *string etc..), is this possible using only one type (var p pointer) for all the pointer types?

What is the difference between different pointer types?

package main

import "fmt"

func main() {
    i := 5
    s := "abc"

    var pi *int      // alternatively var pi pointer
    var ps *string   // alternatively var ps pointer 

    pi = &i
    ps = &s
 
	fmt.Printf("%p %p", pi, ps)  // result is 0x1040e0f8 0x1040a120
}

答案1

得分: 2

Go语言的类型系统旨在防止与指针相关的内存错误。这使得程序员在允许垃圾回收器处理繁重工作的同时,有足够的控制权来操作内存中的对象。如果需要手动管理内存并转换指针类型,可以使用unsafe包

英文:

The type system in Go is designed to prevent memory errors relating to pointers. This allows programmers to have enough control to manipulate objects in memory while Allowing the garbage collector top cop moody of the heavy lifting.
If you need to manually memory and convert pointer types you can use the unsafe package.

答案2

得分: 1

这是可能的,只使用一种类型来处理所有的指针类型。是的,这基本上是C语言的工作原理。不幸的是,这使得语言变得危险。假设你有一个包含10个字节的数组。如果你只传递指针,其他代码就不知道可以安全访问多少字节。这会导致各种缓冲区溢出错误(例如HeartBleed)。

在Go语言中,指针知道它所指向的对象的类型,因此它可以始终防止代码出现缓冲区溢出问题。

你可以按照你的意愿去做,但是只能使用Unsafe包。正如其名称所示,这是一种非常危险的做法。

也许如果你发布你实际想要做的事情,人们可以帮助你。使用不安全的指针并不是编写高性能代码的唯一方法。

英文:

> is this possible using only one type for all the pointer types?

Yes, that is pretty much how C works. Unfortunately, that makes the language dangerous. Say you have an array of 10 bytes. If you JUST pass the pointer, the other code won't know how many bytes it's safe to access. That leads to all kinds of buffer overflow errors. (i.e. HeartBleed)

In Go, they pointer knows the type of the thing it points to, so it can prevent your code from having buffer overflow problems all the time.

You can do what you want, but only by using the Unsafe package. As the name suggests, that is a very dangerous thing to do.

Perhaps if you post what you are ACTUALLY trying to do, people can help you. Using unsafe pointers is not the only way to write performant code.

huangapple
  • 本文由 发表于 2016年11月14日 00:03:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/40575845.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定