iota는 정수뿐만 아니라 부동소수점 타입에도 사용할 수 있고 계산식과 혼합하여 사용할 수도 있다.
type ByteSize int64 const ( _ = iota // ignore KB ByteSize = 1 << (10 * iota) // 1 << (10 * 1) = 1024 MB // 1 << (10 * 2) = 1048576 GB // 1 << (10 * 3) = 1073741824 TB // 1 << (10 * 4) = 1099511627776 PB // 1 << (10 * 5) = 1125899906842624 EB // 1 << (10 * 6) = 1152921504606846976 ) const ( DEFAULT_RATE = 5 + 0.3 * iota // 5 GREEN_RATE // 5.3 SILVER_RATE // 5.6 GOLD_RATE // 5.9 )
iota로 비트 상태를 표현하는 상수를 정의할 수도 있다.
package main import "fmt" const ( // iota로 비트 연산의 결괏값을 상수로 선언 Running = 1 << iota // 1 << 0 == 1 Waiting // 1 << 1 == 2 Send // 1 << 2 == 4 Receive // 1 << 3 == 8 ) func main() { // OR 연산자(|)로 stat 변수 생성 stat := Running | Send display(stat) } func display(stat int) { // AND 연산자(&)로 stat에 포함된 비트 값의 상태 출력 if stat&Running == Running { fmt.Println("Running") } if stat&Waiting == Waiting { fmt.Println("Waiting") } if stat&Send == Send { fmt.Println("Send") } if stat&Receive == Receive { fmt.Println("Receive") } }
실행 결과
Running
Send
이 예제에서는 상수 네 개(Running, Waiting, Send, Receive)를 그룹으로 선언했다. 상수 그룹에는 비트 연산의 결과가 할당되게 했고, 각 비트 연산의 피연산자로 iota를 사용하여 0부터 1씩 증가하게 했다. main 함수에서는 OR 연산자(|)로 stat 변수를 생성했고, display 함수에서는 AND 연산자(&)로 stat에 포함된 비트 값의 상태를 출력했다.