Golang: Trying to create a name, age tuple with zip functionality similar to python

Viewed 382

I have two data elements like

"bob julie mark mike"

And

"20,30,40,50"

And I split them, now I am trying to achieve to return a python:zip type result something like below

[("bob", "20"), ("julie", "30"), ("mark", "40"), ("mike", "50)]

I have tried with below code, but I am getting error unexpected comma, expecting ) at line namesAgesTuple[index] = stringTuple[(value, b[index])]

below is complete code

package main

import (
    "fmt"
    "strings"
)

type stringTuple struct {
    names string
    ages  string
}

func main() {
    var names string = "bob julie mark mike"
    namesArray := strings.Split(names, " ")
    fmt.Println(namesArray)

    var ages string = "20,30,40,50"
    agesArray := strings.Split(ages, ",")
    fmt.Println(agesArray)

    namesAges := make(map[string]string)

    println(len(namesArray))
    println(len(agesArray))
    print(namesAges)

    fmt.Println(zip(namesArray, agesArray))

}

func zip(a []string, b []string) ([]stringTuple, error) {

    if len(a) != len(b) {
        return nil, fmt.Errorf("zip: arguments length must be same ")
    }

    namesAgesTuple := make(map[int][]stringTuple)

    for index, value := range a {
        namesAgesTuple[index] = stringTuple[(value, b[index])]
    }
    fmt.Println(namesAgesTuple)
    return namesAgesTuple, nil

}

Any help greatly appreciated.

Thank you.

1 Answers

Go doesn't have tuple syntax, perhaps you want something like:

stringTuple{value, b[index]}

Since stringTuple is a struct, this is initializing its fields; you could also provide field names explicitly as in:

stringTuple{names: value, ages: b[index]}

Another problem in your code is that namesAgesTuple is a map from int to a slice of stringTuple. But the function just returns a slice, so I'm not sure why you're using a map there.

I'd probably write the code something like this (Go playground link):

type stringTuple struct {
    names string
    ages  string
}

func main() {
    var names string = "bob julie mark mike"
    namesArray := strings.Split(names, " ")
    fmt.Println(namesArray)

    var ages string = "20,30,40,50"
    agesArray := strings.Split(ages, ",")
    fmt.Println(agesArray)

    fmt.Println(zip(namesArray, agesArray))
}

func zip(a []string, b []string) ([]stringTuple, error) {
    if len(a) != len(b) {
        return nil, fmt.Errorf("zip: arguments length must be same ")
    }

    var namesAges []stringTuple
    for index, value := range a {
        namesAges = append(namesAges, stringTuple{value, b[index]})
    }
    return namesAges, nil
}
Related