Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to assign to a regular variable and slice in the same statement?

I’m making a chess game and I want to do a series of type assertions in the same var statement, then pass them to a function that handles it, but apparently, Go doesn’t allow me to assign to a regular variable and a slice index in the same statement:

// inside a function:
asserts := make([]bool, 0, 10)
assertionHandler := func(ok *[]bool) {
    for _, b := range *ok {
        if !b {
            msg := "pieceCliked: failed while trying to do type assertion\n%s\n\n"
            utils.LogPrintError(errors.New(fmt.Sprintf(msg, string(debug.Stack()))))
        }
    }
    *ok = make([]bool, 0, 10)
}

var (
    possibleSquares []string
    // The following results in a syntax error: expected type, found '='
    dataObject, asserts[0]  = data.(map[string]any) 
    playerData, asserts[1]  = dataObject["playerData"].(map[string]any)
    square, asserts[2]      = playerData["selectedPieceLocation"].(string)
    piece, asserts[3]       = playerData["selectedPiece"].(string)
    color, asserts[4]       = playerData["selectedPieceColor"].(string)
)
assertionHandler(asserts)

Is it possible to do what I’m trying to do?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Not the way you’re doing it, no. A var block defines new variables and their types, but you’re trying to assign to both new variables with no types (hence the error expected type) and elements of an existing slice within that block.

You could do:

var (
    possibleSquares []string
    dataObject map[string]any
    playerData map[string]any
    square string
    piece string
    color string
)

dataObject, asserts[0]  = data.(map[string]any) 
playerData, asserts[1]  = dataObject["playerData"].(map[string]any)
square, asserts[2]      = playerData["selectedPieceLocation"].(string)
piece, asserts[3]       = playerData["selectedPiece"].(string)
color, asserts[4]       = playerData["selectedPieceColor"].(string)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading