function - 如何定义返回 map 的函数

标签 function dictionary go

我正在尝试定义一个返回初始化映射的函数:

package main

import "fmt"
import "os"

func defaults() map {
  m := make(map[string]string)
  m["start"] = "1"
  m["from"]  = "encrypted"
  m["to"]    = "loaded"
  return m
}

func main() {
  args := os.Args[1:]
  fmt.Println(args)
  runvals := defaults()
  fmt.Println(runvals)
}

我遇到的错误:

Line 6 col 21 error| expected '[', found '{'
Line 7 col 5 error| expected ']', found ':='
Line 11 col 3 error| expected declaration, found 'return'

谁能帮我弄清楚语法?还是我正在尝试做一些 Go 不会做的事情?

最佳答案

您需要声明整个类型,包括键和值类型。

func defaults() map[string]string {
    …
}

关于function - 如何定义返回 map 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43095764/

相关文章:

php - Code-Golf:一行 PHP 语法

python - 如何将字典键与函数相关联?

python - 我们可以在 Python 中使用并发和混合的字典吗?

file - 写入文件然后立即读回

Javascript 函数无法运行

perl - 将代码转换为 perl sub,但不确定我是否做对了

根据 R 中的名称向量删除列

python - 如何在 python 中将值列表转换为字典?

go - 如何使 fmt.Scanln() 读入一片整数

go - 将堆栈跟踪放入字符串变量