stringgoslice

how to add all thing in slice to an only one string


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


Solution

  • info[2:] will return a string slice when your map expects a complete string. To resolve the error and accept the full name of the Book, you might want to join the slice obtained from info[2:] to form a full string. Thus, using strings.Join(info[2:], " ") will solve the issue.

    updated code piece:

    mymap[z] = strings.Join(info[2:], " ")