如何定义一个返回映射(map)的函数

huangapple go评论71阅读模式
英文:

How to define a function which returns a map

问题

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

package main

import "fmt"
import "os"

func defaults() map[string]string {
  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)
}

我遇到的错误:

第6行第21列错误| 预期 '[', 发现 '{'
第7行第5列错误| 预期 ']', 发现 ':='
第11行第3列错误| 预期声明,发现 'return'

有人可以帮我纠正语法吗?或者我是在尝试做一些Go不支持的事情吗?

英文:

I am attempting to define a function which returns an initialized map:

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

Errors I'm getting:

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

Can someone help me get the syntax right? Or am I trying to do something that Go doesn't do?

答案1

得分: 2

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

func defaults() map[string]string {
    
}
英文:

You need to declare the whole type including key and value types.

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

答案2

得分: 0

你的defaults函数存在问题,返回类型map没有指定类型。

英文:
func defaults() map[string] string {
    m := make(map[string]string)
    m["start"] = "1"
    ...
    return m
}

The problem with your defaults function is the return type map has no types.

huangapple
  • 本文由 发表于 2017年3月29日 22:01:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/43095764.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定