Search code examples
dictionarygoiteratorreversegolang-migrate

Use a interator propeties in a cunston type


I was writing Go code where I created a type using base map [string] int and I need to create a method that returns a map, reversing key and value. I started writing the code, but I can't iterate the type I created.

So far I've made the following code:

package constants

type Month map[string]int;

// LongMonth is a relationship with string and date value (int)
var LongMonth = Month{
    "Janary":1,
    "February":2,
    "March":3,
    "April":4, 
    "May":5,
    "June": 6,
    "July": 7,
    "August": 8,
    "September": 9,
    "Octuber": 10,
    "Novenber": 11,
    "Decenber": 12,
}

// ShortMonth is a relationship with a resume string and date value (int)
var ShortMonth = Month{
    "Jan":1,
    "Feb":2,
    "Mar":3,
    "Apr":4, 
    "May":5,
    "Jun": 6,
    "Jul": 7,
    "Aug": 8,
    "Sep": 9,
    "Oct": 10,
    "Nov": 11,
    "Dec": 12,
}

func (m* Month) Reverse() map[int]string {
    n:=make(map[int]string);
    for k, v := range m {
        n[v] = k
    }
    return n
};
// LongMonthReverse is a relationship with string and date value (int)
// var LongMonthReverse = reverseMonth(LongMonth);
// ShortMonthReverse is a relationship with string and date value (int)
// var ShortMonthReverse = reverseMonth(ShortMonth);

i need function Reverse return the revers emonth. Ex: month = {"Jan": 1..."Dec": 12} and month.Reverse() returns {1: "Jan"....12: "Dec"}


Solution

  • You can't iterate over a pointer either change the method interface of func (m* Month) Reverse() map[int]string to func (m Month) Reverse() map[int]string or you need to use *m inside of Reverse()

    package main
    
    import "fmt"
    
    
    type Month map[string]int
    
    // LongMonth is a relationship with string and date value (int)
    var LongMonth = Month{
        "Janary":1,
        "February":2,
        "March":3,
        "April":4,
        "May":5,
        "June": 6,
        "July": 7,
        "August": 8,
        "September": 9,
        "Octuber": 10,
        "Novenber": 11,
        "Decenber": 12,
    }
    
    // ShortMonth is a relationship with a resume string and date value (int)
    var ShortMonth = Month{
        "Jan":1,
        "Feb":2,
        "Mar":3,
        "Apr":4,
        "May":5,
        "Jun": 6,
        "Jul": 7,
        "Aug": 8,
        "Sep": 9,
        "Oct": 10,
        "Nov": 11,
        "Dec": 12,
    }
    
    func (m* Month) Reverse() map[int]string {
        n:=make(map[int]string)
        // this is the fix
        for k, v := range *m {
            n[v] = k
        }
        return n
    }
    
    
    func main() {
      fmt.Println(ShortMonth.Reverse())
    }