Home > Backend Development > Golang > Create type from slice

Create type from slice

王林
Release: 2024-02-05 22:57:07
forward
792 people have browsed it

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
}
Copy after login


Correct answer


Your push function is not doing anything.

Correct push function:

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

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!

Related labels:
source:stackoverflow.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template