---
title: "go语言常量的使用"
author: "studypi"
date: "2017-08-21T10:34:48Z"
tags: []
categories: ["编程语言"]
slug: "go"
draft: false
lastmod: "2017-08-21T10:41:54Z"
id: 2390497
url: "https://studypi.iteye.com/blog/2390497"
---

常量用<span style="color:red">**const**</span>关键字定义，用于存储不会改变的数据
常量的数据类型一般是bool，数字和字符串
定义的方式：

> const {name} {type} = {value} 或 const {name} = value

也可以多个定义

> const {name1},{name2} {type} = {value1},{value2}

用列子说明：

```java

package main

import (
	"fmt"
	"reflect"
)

const cK string = "string const"
const cj = "string j"
const (
	a int = 1
	b
	c int = iota
	d
)

const (
	e, f, g = 5, "6", 7
)

func main() {
	fmt.Printf("cK:%s,cj:%s,a:%d,b:%d,c:%d,d:%d,e:%d,f:%s,g:%d\n", cK, cj, a, b, c, d, e, f, g)
	fmt.Println(reflect.TypeOf(f))
}

```

结果：

![](http://dl2.iteye.com/upload/attachment/0126/6245/46e6ecf3-8e4a-39cd-bb01-e1544824724b.png)

注意：iota是golang语言的常量计数器,只能在常量的表达式中使用
iota在const关键字出现时将被重置为0(const内部的第一行之前)
reflect包是go的反射包，reflect.TypeOf反射数据类型