Go에서 포인터를 사용하는 이유는 무엇입니까?
Go의 포인터가 함수 인수의 변형을 허용한다는 것을 알고 있지만 참조 (적절한 const 또는 가변 한정자 포함) 만 채택하면 더 간단하지 않을 것입니다. 이제 포인터와 맵 및 채널과 같은 일부 내장 유형에 대해 암시 적으로 참조로 전달합니다.
내가 뭔가를 놓치고 있거나 Go의 포인터가 불필요한 복잡성입니까?
http://www.golang-book.com/8 에서 가져온 예를 정말 좋아합니다 .
func zero(x int) {
x = 0
}
func main() {
x := 5
zero(x)
fmt.Println(x) // x is still 5
}
대조적으로
func zero(xPtr *int) {
*xPtr = 0
}
func main() {
x := 5
zero(&x)
fmt.Println(x) // x is 0
}
참조는 재 할당 할 수 없지만 포인터는 지정할 수 있습니다. 이것만으로도 참조를 사용할 수없는 많은 상황에서 포인터가 유용합니다.
포인터는 여러 가지 이유로 유용합니다. 포인터를 사용하면 메모리 레이아웃을 제어 할 수 있습니다 (CPU 캐시의 효율성에 영향을 미침). Go에서 모든 멤버가 연속 메모리에있는 구조를 정의 할 수 있습니다.
type Point struct {
x, y int
}
type LineSegment struct {
source, destination Point
}
이 경우 Point
구조체는 LineSegment
구조체 내에 포함됩니다 . 그러나 항상 데이터를 직접 포함 할 수는 없습니다. 이진 트리 또는 연결 목록과 같은 구조를 지원하려면 일종의 포인터를 지원해야합니다.
type TreeNode {
value int
left *TreeNode
right *TreeNode
}
Java, Python 등은 복합 유형을 포함 할 수 없기 때문에이 문제가 없으므로 포함과 포인팅을 구문 적으로 구분할 필요가 없습니다.
Go 포인터로 해결 된 Swift / C # 구조체 문제
이를 달성하기위한 가능한 대안을 구별하는 것이다 struct
및 class
C # 및 스위프트처럼. 그러나 여기에는 한계가 있습니다. 일반적으로 함수가 구조체를 inout
매개 변수로 사용하여 구조체를 복사하지 않도록 지정할 수 있지만 구조체에 대한 참조 (포인터)를 저장할 수는 없습니다. 즉, 풀 할당자를 만드는 데 유용하다고 생각되면 구조체를 참조 유형으로 처리 할 수 없습니다 (아래 참조).
커스텀 메모리 할당 자
포인터를 사용하여 고유 한 풀 할당자를 만들 수도 있습니다 (원칙을 보여주기 위해 많은 검사를 제거하여 매우 단순화 됨).
type TreeNode {
value int
left *TreeNode
right *TreeNode
nextFreeNode *TreeNode; // For memory allocation
}
var pool [1024]TreeNode
var firstFreeNode *TreeNode = &pool[0]
func poolAlloc() *TreeNode {
node := firstFreeNode
firstFreeNode = firstFreeNode.nextFreeNode
return node
}
func freeNode(node *TreeNode) {
node.nextFreeNode = firstFreeNode
firstFreeNode = node
}
두 값 바꾸기
포인터를 사용하면 swap
. 그것은 두 변수의 값을 바꾸는 것입니다.
func swap(a *int, b *int) {
temp := *a
*a = *b
*b = temp
}
결론
Java has never been able to fully replace C++ for systems programming at places such as Google, in part because performance can not be tuned to the same extend due to the lack of ability to control memory layout and usage (cache misses affect performance significantly). Go has aimed to replace C++ in many areas and thus needs to support pointers.
Go is designed to be a terse, minimalist language. It therefore started with just values and pointers. Later, by necessity, some reference types (slices, maps, and channels) were added.
"There's a lot of history on that topic. Early on, maps and channels were syntactically pointers and it was impossible to declare or use a non-pointer instance. Also, we struggled with how arrays should work. Eventually we decided that the strict separation of pointers and values made the language harder to use. Introducing reference types, including slices to handle the reference form of arrays, resolved these issues. Reference types add some regrettable complexity to the language but they have a large effect on usability: Go became a more productive, comfortable language when they were introduced."
Fast compilation is a major design goal of the Go programming language; that has its costs. One of the casualties appears to be the ability to mark variables (except for basic compile time constants) and parameters as immutable. It's been requested, but turned down.
golang-nuts : go language. Some feedback and doubts.
"Adding const to the type system forces it to appear everywhere, and forces one to remove it everywhere if something changes. While there may be some benefit to marking objects immutable in some way, we don't think a const type qualifier is to way to go."
참고URL : https://stackoverflow.com/questions/1863460/whats-the-point-of-having-pointers-in-go
'code' 카테고리의 다른 글
* 4GB 이상의 * 파일을 지원하는 최고의 무료 텍스트 편집기? (0) | 2020.09.25 |
---|---|
스타일 설정 기에서 블렌드 비헤이비어를 추가하는 방법 (0) | 2020.09.25 |
디렉토리와 폴더의 차이점은 무엇입니까? (0) | 2020.09.25 |
힘내 풀과 힘내 리베이스 (0) | 2020.09.25 |
Windows의 응용 프로그램에 Ctrl-C (SIGINT)를 보낼 수 있습니까? (0) | 2020.09.25 |