I'm trying to make a list of Strings in golang. I'm looking up the package container/list but I don't know how to put in a string. I tried several times, but 0 result.
Should I use another thing instead of lists? Thanks in advance.
edit: Don't know why are you rating this question with negatives votes...
If you take a look at the source code to the package you linked, it seems that the List
type holds a list of Element
s. Looking at Element
you'll see that it has one exported field called Value
which is an interface{}
type, meaning it could be literally anything: string
, int
, float64
, io.Reader
, etc.
To answer your second question, you'll see that List
has a method called Remove(e *Element)
. You can use it like this:
fmt.Println(l.Len()) // prints: 4
// Iterate through list and print its contents.
for e := l.Front(); e != nil; e = e.Next() {
if e.Value == "4" {
l.Remove(e) // remove "4"
} else {
fmt.Println(e.Value)
}
}
fmt.Println(l.Len()) // prints: 3
By and large, Golang documentation is usually pretty solid, so you should always check there first.
Modifying the exact example you linked, and changing the ints to strings works for me:
package main
import (
"container/list"
"fmt"
)
func main() {
// Create a new list and put some numbers in it.
l := list.New()
e4 := l.PushBack("4")
e1 := l.PushFront("1")
l.InsertBefore("3", e4)
l.InsertAfter("2", e1)
// Iterate through list and print its contents.
for e := l.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
}