Home  >  Article  >  Backend Development  >  How to Modify a Simple Type\'s Value Using a Pointer Receiver in Go?

How to Modify a Simple Type\'s Value Using a Pointer Receiver in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 11:32:02454browse

How to Modify a Simple Type's Value Using a Pointer Receiver in Go?

Modifying Value of a Simple Type through Pointer Receiver in Go

Modifying the value of a simple type through a pointer receiver method can be a common task in Go. However, understanding how pointers behave in this context is crucial.

In the provided example:

<br>type FooInt int</p>
<p>func (fi *FooInt) FromString(i string) {</p>
<pre class="brush:php;toolbar:false">num, _ := strconv.Atoi(i)
tmp := FooInt(num)
fi = &tmp

}

When a pointer is passed as a receiver, a copy of that pointer is created within the method. Any modifications made to the copy inside the method will not affect the original pointer.

In the code snippet, *fi is a copy of the fi pointer passed to the FromString method. When you assign &tmp to *fi, you are essentially changing the copy's value, not the original fi pointer.

To modify the original pointer's value, you need to either:

  • Return the new pointer value:

    <br>  func (fi <em>FooInt) FromString(i string) </em>FooInt {</p>
    <pre class="brush:php;toolbar:false">  num, _ := strconv.Atoi(i)
      tmp := FooInt(num)
      return &tmp

    }

  • Pass a non-nil pointer to the value you want to change:

    <br>  func (fi <em>FooInt) FromString(i string, p </em>*FooInt) {</p>
    <pre class="brush:php;toolbar:false">  num, _ := strconv.Atoi(i)
      tmp := FooInt(num)
      *p = &tmp

    }

  • Ensure the receiver is not nil:

    <br>  func (fi *FooInt) FromString(i string) {</p>
    <pre class="brush:php;toolbar:false">  num, _ := strconv.Atoi(i)
      *fi = FooInt(num)

    }

By ensuring that the receiver is a valid pointer and modifying the pointed value inside the method, you can effectively modify the value of the original simple type through a pointer receiver.

The above is the detailed content of How to Modify a Simple Type\'s Value Using a Pointer Receiver in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn