简体   繁体   中英

Initializing single element of string array into another string variable in Go lang

In this code, I read a text file for input (A1,B2) and Im using the split function to separate them at comma and store in strs, according to the function definition its returns a array in this case it is strs array, i want the first element in strs to be in currentSource and the second element to be in CurrentDest.I tried printing both the variables individually to check if its working,but the program exits after that and I get a error saying Panic: index out of range. Can anybody help me out..!!!

var currentSource string
var currentDest string

func main() {

    file, err := os.Open("chessin.txt")
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        strs := strings.Split(scanner.Text(), ",")

        currentSource = strs[0]
        currentDest = strs[1]
}

This works

var currentSource string
var currentDest string

func main() {

    file := "A1,B2\n"
    scanner := bufio.NewScanner(strings.NewReader(file))
    for scanner.Scan() {
        strs := strings.Split(scanner.Text(), ",")

        currentSource = strs[0]
        currentDest = strs[1]

        fmt.Println(strs)
    }


}

Are you sure your file ( chessin.txt ) it is ok?

Playground

This code is almost the same as your code and it works correctly:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

var currentSource string
var currentDest string

func main() {

    // content of this file is (no spaces between comas, not \r or
    // \n or any other whitespace):
    //C3,F3,C4,A4,C5,A1
    file, err := os.Open("chessin.txt")
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        strs := strings.Split(scanner.Text(), ",")

        if len(strs) < 2 {
            panic(`not enough elements in the file, to proceed`)
        }

        currentSource = strs[0]
        currentDest = strs[1]

        break //(B)
    }

    if currentSource != "C3" {
        panic(`currentSource IS NOT C3`)
    }

    if currentDest != "F3" {
        panic(`currentDest is not F3`)
    }

    // if we are here, then we are good
    fmt.Println(currentSource, currentDest)
}

Just pay attention to the break statement at (B) . That causes the for loop to stop, after the first and second elements of the first line - not sure; but that might be what you want.

So, if the program does not reach the (A) point, then there something wrong with chessin.txt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM