【问题标题】:Use a interator propeties in a cunston type在自定义类型中使用迭代器属性
【发布时间】:2020-01-04 17:40:46
【问题描述】:

我正在编写 Go 代码,其中我使用基本映射 [string] int 创建了一个类型,我需要创建一个返回映射、反转键和值的方法。我开始编写代码,但无法迭代我创建的类型。

到目前为止,我已经编写了以下代码:

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);

我需要函数 Reverse 返回revers emonth。例如:month = {"Jan": 1..."Dec": 12} 和 month.Reverse() 返回 {1:"Jan"....12:"Dec"}

【问题讨论】:

  • 您不能使用m 作为范围的值,因为它的类型是*Month。我建议将方法的签名更改为 func (m Month) Reverse() map[int]string

标签: dictionary go iterator reverse golang-migrate


【解决方案1】:

您不能迭代指针,要么将func (m* Month) Reverse() map[int]string 的方法接口更改为func (m Month) Reverse() map[int]string,要么您需要在Reverse() 内部使用*m

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())
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 2021-06-19
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多