Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang - mapping an variable length array to a struct

Tags:

go

I have a struct as follows:

type MyStruct struct {
   Part1 string
   Part2 string
   Part3 string
}

I have a string separated by slashes that I want to map to this:

part1/part2/part3

However, the string may only contain 1 part such as part1 or two parts such as part1/part2

if any part is missing it much be mapped as an empty string.

I am very new to go so wondering what the best way to achieve this is. Typically i would split the string and check the length to know what to do. In go is there a more elegant way to do this?

like image 757
Marty Wallace Avatar asked Feb 03 '26 01:02

Marty Wallace


1 Answers

Here's a version of peterSO's solution that uses a wrapper to help simplify the logic.

package main

import (
    "fmt"
    "strings"
)

type Wrap []string

func (w Wrap) Get(i int) string {
    if 0 <= i && i < len(w) {
        return w[i]
    }
    return ""
}

type MyStruct struct {
    Part1 string
    Part2 string
    Part3 string
}

func main() {
    str := "part1/part2/part3"
    split := Wrap(strings.Split(str, "/"))
    var parts MyStruct
    parts.Part1 = split.Get(0)
    parts.Part2 = split.Get(1)
    parts.Part3 = split.Get(2)
    fmt.Println(parts)

    str = "part1/part2"
    split = Wrap(strings.Split(str, "/"))
    parts = MyStruct{}
    parts.Part1 = split.Get(0)
    parts.Part2 = split.Get(1)
    parts.Part3 = split.Get(2)
    fmt.Println(parts)
}
like image 199
dyoo Avatar answered Feb 05 '26 13:02

dyoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!