Table of Contents
Correct answer
Home Backend Development Golang Create type from slice

Create type from slice

Feb 05, 2024 pm 10:57 PM
Compile Error string class overflow

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1652
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Function name definition in c language Function name definition in c language Apr 03, 2025 pm 10:03 PM

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

Is H5 page production a front-end development? Is H5 page production a front-end development? Apr 05, 2025 pm 11:42 PM

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

How to customize the resize symbol through CSS and make it uniform with the background color? How to customize the resize symbol through CSS and make it uniform with the background color? Apr 05, 2025 pm 02:30 PM

The method of customizing resize symbols in CSS is unified with background colors. In daily development, we often encounter situations where we need to customize user interface details, such as adjusting...

Why are the inline-block elements misaligned? How to solve this problem? Why are the inline-block elements misaligned? How to solve this problem? Apr 04, 2025 pm 10:39 PM

Regarding the reasons and solutions for misaligned display of inline-block elements. When writing web page layout, we often encounter some seemingly strange display problems. Compare...

How to use the clip-path attribute of CSS to achieve the 45-degree curve effect of segmenter? How to use the clip-path attribute of CSS to achieve the 45-degree curve effect of segmenter? Apr 04, 2025 pm 11:45 PM

How to achieve the 45-degree curve effect of segmenter? In the process of implementing the segmenter, how to make the right border turn into a 45-degree curve when clicking the left button, and the point...

How to control the top and end of pages in browser printing settings through JavaScript or CSS? How to control the top and end of pages in browser printing settings through JavaScript or CSS? Apr 05, 2025 pm 10:39 PM

How to use JavaScript or CSS to control the top and end of the page in the browser's printing settings. In the browser's printing settings, there is an option to control whether the display is...

How to achieve segmentation effect with 45 degree curve border? How to achieve segmentation effect with 45 degree curve border? Apr 04, 2025 pm 11:48 PM

Tips for Implementing Segmenter Effects In user interface design, segmenter is a common navigation element, especially in mobile applications and responsive web pages. ...

Issues with Dev-C version Issues with Dev-C version Apr 03, 2025 pm 07:33 PM

Dev-C 4.9.9.2 Compilation Errors and Solutions When compiling programs in Windows 11 system using Dev-C 4.9.9.2, the compiler record pane may display the following error message: gcc.exe:internalerror:aborted(programcollect2)pleasesubmitafullbugreport.seeforinstructions. Although the final "compilation is successful", the actual program cannot run and an error message "original code archive cannot be compiled" pops up. This is usually because the linker collects

See all articles