Home  >  Article  >  Backend Development  >  Create type from slice

Create type from slice

王林
王林forward
2024-02-05 22:57:07712browse

Create type from slice

Question content

I want to create a data type like a stack. I want to add and remove entries "at the top" and be able to print them out. In this example, the xpath type is used to traverse the xml document and keep track of the current path.

So I created an xpath[]string type and wrote the corresponding functions, namely: push() pop() and string().

My problem is that the type loses its state, which confuses me a bit since I thought slices were reference types. Also, if I try to change the function to a pointer receiver, I get several compilation errors. To fix this at this point I just changed the []string to a struct with a single []string field. Although it still bothers me that I can't get it to work using just slice as the base type.

What is the correct approach?

package main

import (
    "fmt"
    "strings"
)

type xPath []string

func (xp xPath) push(entry string) {
    xp = append(xp, entry)
}

func (xp xPath) String() string {
    sb := strings.Builder{}
    sb.WriteString("/")
    sb.WriteString(strings.Join(xp, "/"))
    return sb.String()
}

func main() {
    xp := xPath{}
    xp.push("rss")
    xp.push("channel")
    xp.push("items")
    fmt.Println(xp)

    // Output: /
    // Wanted: /rss/channel/items
}

Correct answer


Your push function is not doing anything.

Correct push function:

func (xp *xPath) push(entry string) {
    *xp = append(*xp, entry)
}

Slices are reference types in situations where you want to change their value (e.g. using an index).

On the other hand, if you want to reallocate them and replace the entire slice, you should use pointers.

Regarding the stack, there are some better ways: Take a look at this question.

The above is the detailed content of Create type from slice. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete