乐闻世界logo
搜索文章和话题

How do you define constants in Go?

1个答案

1

In Go, constants are defined using the const keyword. Constants can be of character, string, boolean, or numeric types, and once assigned, their values cannot be changed. The general form for defining constants is as follows:

go
const Pi = 3.14

You can also define multiple constants within a const block, which makes the code more organized. For example:

go
const ( StatusOK = 200 StatusNotFound = 404 StatusError = 500 )

In Go, constant naming conventions typically follow camelCase. If a constant is exported (accessible in other packages), its first letter should be uppercase.

Additionally, Go supports enumerated constant types, which is achieved using the special iota keyword. iota is reset to 0 when a const block begins, and increments automatically for each new constant declaration within the block:

go
const ( North = iota // 0 East // 1 South // 2 West // 3 )

Here, iota is used to represent directions, with values incrementing sequentially from 0.

Using constants can improve program performance because the values are determined at compile time and do not require computation at runtime. Additionally, using constants can enhance code readability and maintainability.

2024年8月7日 18:16 回复

你的答案