hello every body i was coding about create a map and on that map we have 2 thing name of book and number of book and i stuck in one thing if name of book is look like this “Harry Potter” only my code add Harry and i think to add all thing after Harry in my slice but golang give error and said you cant add slice to map only you can add one string thing and i dont know how to fix it
this is my code
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
//how much data you want add and delete
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
num, _ := strconv.Atoi(scanner.Text())
mymap := make(map[int]string)
for i := 0; i < num; i++ {
scanner.Scan()
info := strings.Fields(scanner.Text())
//if he want to add datas
if info[0] == "ADD" {
var z, _ = strconv.Atoi(info[1])
mymap[z] = info[2]
//if he want remove datas
} else if info[0] == "REMOVE" {
x := info[1]
var z, _ = strconv.Atoi(x)
delete(mymap, z)
}
}
fmt.Println(mymap)
}
so i do
mymap[z] = info[2:]
but its not work and this is my problem
Sepehr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
info
will be a []string
e.g. {"ADD", "1", "Harry", "Potter"}
and you want to convert info[2:]
into a string
(i.e. “Harry Potter”) with the elements separated by spaces (partly reversing strings.Fields
). strings.Join
is probably the simplest approach (playground):
func main() {
testInput := []string{ // simulate input
"ADD 1 Harry Potter",
"ADD 1 Harry Potter",
"ADD 1 Lord of the rings",
"REMOVE 2 Harry Potter",
}
mymap := make(map[int]string)
for _, command := range testInput {
info := strings.Fields(command)
//if he want to add datas
if info[0] == "ADD" {
var z, _ = strconv.Atoi(info[1])
mymap[z] = strings.Join(info[2:], " ")
//if he want remove datas
} else if info[0] == "REMOVE" {
x := info[1]
var z, _ = strconv.Atoi(x)
delete(mymap, z)
}
}
fmt.Println(mymap)
}
Note: The resulting string may not exactly match your input (e.g. multiple spaces would be lost) but this may not matter for your use case.
I would note that your code is probably not doing what you want. Consider
ADD 1 Harry Potter
ADD 1 Lion Witch
ADD 1 Lord of the rings
Will result in map[1:Lord of the rings]
(probably not what you want).