Home > database >  Go: panic: runtime error: index out of range [1] with length 1
Go: panic: runtime error: index out of range [1] with length 1

Time:06-25

I am a beginner, and i don't know how to solve this problem, i hope you can explain it in a easy way.

this is what i want to:

my project is to create a program that can let user open multiple folder at once, the user can type the list of filename they want in fmt.Scanln(&input_filename)

strings.Fields(input_filename) will seprate the user input into list

len(filename) will get the length of the list

Code:

var folderpath string
var input_filename string
var list_length int

func main() {

    fmt.Print("Type where you want your folders to be created: ")
    fmt.Scanln(&folderpath)
    fmt.Print("Type the filename you desired: ")
    fmt.Scanln(&input_filename)

    filename := strings.Fields(input_filename)

    list_length = len(filename)

    for x := 0; x < list_length 1; x   {
        createfolder := folderpath   filename[x]
        if _, err := os.Stat(createfolder); errors.Is(err, os.ErrNotExist) {
            err := os.Mkdir(createfolder, os.ModePerm)
            if err != nil {
                log.Println(err)
            }
        }
        fmt.Println(strconv.Itoa(list_length)   " "   "folders created suscessfully")
    }
}

Output:

Type where you want your folders to be created: C:/Users/[username]/Documents/Sandbox/
Type the filename you desired: test1 test2 test3
1 folders created suscessfully
panic: runtime error: index out of range [1] with length 1

goroutine 1 [running]:
main.main()
        C:/Users/[username]/Documents/create-folder/main.go:28  0x2ec
PS C:\Users\[username]\Documents\create-folder> go build main.go

and only test1 folder show up at the end

CodePudding user response:

Arryay indexes started from "0".

CodePudding user response:

I can understand that you are getting the error at this position

 for x := 0; x < list_length 1; x   {
        createfolder := folderpath   filename[x]

can I know why are you using 1 there in the for loop ? if you can avoid it in some way, you should be able to build the code peacefully, because that is the only root cause I see.

  • Related