Go language learning seven – go Stack

package stack

import "errors"

type Stack []interface{}

func (s *Stack) Len() int {
	return len(*s)
}

func (s *Stack) Cap() int {
	return cap(*s)
}

func (s *Stack) Push(x interface{}) *Stack {

	*s = append(*s, x)

	/**

	If it is changed toZ: = append (*s, x)S = & Z1. Instead of assigning a function return value to a variable, address a function directly: like this: s = amp; (append (* s, x))It is not allowed.The reason may be that the return value of a function is a local variable that is scoped inside the function, and if no value is passed to an external caller after the function ends, the scope ends (and the space is reclaimed by GC)It is not possible to get addresses from such local variables.IfThe return value is directly a pointer (address) that can of course be assigned directly to an external variable, so you should be able to value the function that returns the pointer as followsFunc foo1 () *int {X: = 4; return & X}FunC foo2 () int {X: = 4; return x}Fmt.Println (*foo1 ()) //okFmt.Println (& foo2 ()) //no2. modify the address directly, externally.S: = stack.Stack{1, 2, 3}S.Push (4).Push (5).Push (6)Fmt.Println (s)The return is still {1,2,3}.The reason for this is that although the recipient of the method is a pointer, the method itself is simply referring to the value of the address passed in.Inside the method you can use this incoming address value to modify the memory in which the address is located, but if you doChange address to itselfBut it has no effect on the outside world. In short, from this point of view, a high school student who used to learn C language said:"Fundamentally, functions are all called by value, but sometimes they are passed as variable values and sometimes as address values."* * /RetuRN s}Func (s *Stack) Top () (interface{}, error) {N: = s.Len ()If n = = 0 {{Return nilErrors.New ("can not get top from an empty stack")}Return (*s) [n-1], nil}Func (s *Sta)CK) Pop () (interface{}, error) {N: = s.Len ()If n = = 0 {{Return nil, errors.New ("can not p"OP an empty stack ""}Top: = (*s) [n-1]*s = (*s) [: n-1]Return top, nil}

  

Leave a Reply

Your email address will not be published. Required fields are marked *