如何在golang中声明常量映射 [英] How to declare constant map in golang

查看:578
本文介绍了如何在golang中声明常量映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是golang的新手。我正在努力声明不断进行。但它正在抛出一个错误。任何人都可以帮助我使用声明常量的语法吗?

这是我的代码:

 const romanNumeralDict map [int] string = {
1000:M,
900:CM,
500:D,
400:CD,
100:C,
90:XC,
50:L,
40:XL,
10:X,
9:IX,
5:V,
4:IV,
1:I,

$ / code>

这是错误

 #命令行参数
./Roman_Numerals.go:9:语法错误:意外的{


解决方案

您的语法不正确。要创建一个文字图(作为伪常量),您可以这样做:

  var romanNumeralDict = map [int] string { 
1000:M,
900:CM,
500:D,
400:CD,
100:C,
90:XC,
50:L,
40:XL,
10:X,
9:IX,
5:V,
4:IV,
1:I,
}

func 中,您可以声明它:

  romanNumeralDict:= map [int] string {
...

在Go中没有像常量映射那样的东西。有关更多信息,请访问 此处



试试Go the playground。


I am new to the golang. I am trying to declare to constant in go. But it is throwing an error. Could anyone please help me with the syntax of declaring a constant in go?

This is my code:

const romanNumeralDict map[int]string = {
  1000: "M",
  900 : "CM",
  500 : "D",
  400 : "CD",
  100 : "C",
  90  : "XC",
  50  : "L",
  40  : "XL",
  10  : "X",
  9   : "IX",
  5   : "V",
  4   : "IV",
  1   : "I",
}

This is the error

# command-line-arguments
./Roman_Numerals.go:9: syntax error: unexpected {

解决方案

Your syntax is incorrect. To make a literal map (as a pseudo-constant), you can do:

var romanNumeralDict = map[int]string{
  1000: "M",
  900 : "CM",
  500 : "D",
  400 : "CD",
  100 : "C",
  90  : "XC",
  50  : "L",
  40  : "XL",
  10  : "X",
  9   : "IX",
  5   : "V",
  4   : "IV",
  1   : "I",
}

Inside a func you can declare it like:

romanNumeralDict := map[int]string{
...

And in Go there is no such thing as a constant map. More information can be found here.

Try it out on the Go playground.

这篇关于如何在golang中声明常量映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆