dictionary - 在自定义类型中使用迭代器属性

标签 dictionary go iterator reverse golang-migrate

我正在编写 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 返回反向 emonth。例如:month = {"Jan": 1..."Dec": 12} 和 month.Reverse() 返回 {1:"Jan"....12:"Dec"}

最佳答案

您不能迭代指针或者更改 func (m* Month) Reverse() map[int]string 的方法接口(interface)至func (m Month) Reverse() map[int]string或者您需要使用 *m 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())
}

关于dictionary - 在自定义类型中使用迭代器属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593254/

相关文章:

c# - .NET字典插入的怪异性能行为

selenium - 如何使用 gocolly twocaptcha 和 selenium 绕过重新验证码

go - 为什么 'Open connection failed:sql: unknown driver "mssql“(忘记导入?)”会在 go build 中第一次发生?

c++ - 如何在 C++ 中实现自定义标准集合?

python - 生成具有多个列的.CSV-使用字典吗?

hadoop - 如何选择${mapred.local.dir}?

python - 从字典键更新 MySQL 行标题 (Python)

json - 从 url 读取 json

iterator - 遍历集合。 Iterator 被删除后立即删除它

java - CopyOnWriteArrayList 上线程中的迭代器不起作用