在struct的方法中更改struct的指针值 [英] change struct's pointer value in struct's method

查看:177
本文介绍了在struct的方法中更改struct的指针值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将我的头包裹在指针上。

  package main 

import(
fmt


// LinkedList类型
类型LinkedList结构{
数据int
下一个* LinkedList
}

// InsertList将插入一个项目到列表中
func(node * LinkedList)InsertList(data int){
newHead:= LinkedList {data,node}
node =& newHead


func main(){
node:=& LinkedList {}
node.InsertList(4)
fmt.Printf(node =% + v \ n,node)
}

输出是

  node =& {data:0 next:< nil>} 

我想知道为什么 node =& newHead 我的InsertList方法没有引用节点指针到另一个结构

解决方案

接收者节点值就像其他参数一样,所以任何cha您在功能中所做的更改不会被来电者看到。如果你想要一个函数来修改函数外部存在的东西,函数需要处理一个指向该对象的指针。在你的情况中, node 是一个指针,但你真正想要的是指向表示列表本身的东西的指针。例如:

 包主

导入(
fmt


类型LinkedListNode struct {
数据int
下一个* LinkedListNode
}

类型LinkedList结构{
头* LinkedListNode
}

// InsertList将插入一个项目到列表
func(list * LinkedList)InsertList(data int){
newHead:=& LinkedListNode {数据,list.head}
list.head = newHead
}

func main(){
var list LinkedList
list.InsertList(4)
fmt.Printf(node =%+ v \ n,list.head)
list.InsertList(7)
fmt.Printf(node =%+ v \\\
,list.head)
}


I am trying to wrap my head around pointer in go. I have this code right here

package main

import (
    "fmt"
)

// LinkedList type
type LinkedList struct {
    data int
    next *LinkedList
}

// InsertList will insert a item into the list
func (node *LinkedList) InsertList(data int) {
    newHead := LinkedList{data, node}
    node = &newHead
}

func main() {
    node := &LinkedList{}
    node.InsertList(4)
    fmt.Printf("node = %+v\n", node)
}

and The output is

node = &{data:0 next:<nil>}

I would like to understand that why is node = &newHead my InsertList method did not reference the node pointer to a different struct at all

解决方案

The receiver node is passed by value just like other parameters, so any changes you make in the function are not seen by the caller. If you want a function to modify something that exists outside the function, the function needs to be dealing with a pointer to that object. In your case, node is a pointer, but what you really want is a pointer to something that represents the list itself. For example:

package main

import (
    "fmt"
)

type LinkedListNode struct {
    data int
    next *LinkedListNode
}

type LinkedList struct {
    head *LinkedListNode
}

// InsertList will insert a item into the list
func (list *LinkedList) InsertList(data int) {
    newHead := &LinkedListNode{data, list.head}
    list.head = newHead
}

func main() {
    var list LinkedList
    list.InsertList(4)
    fmt.Printf("node = %+v\n", list.head)
    list.InsertList(7)
    fmt.Printf("node = %+v\n", list.head)
}

这篇关于在struct的方法中更改struct的指针值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆