Golang iota

00_8_3·2023년 3월 9일
0

Go

목록 보기
6/10

iota

  • Golang의 상수 생성기.
  • 테이터 타입이 없는 정수를 연속으로 생성해줍니다.
    • 0부터 1씩 증가한다.
const (
        a = iota
        b = iota
        c = iota
    )

출력값
0
1
2

const 사용법

const a = iota
const b = iota
const c = iota

출력값
0
0
0

  • const로 묶어서 사용해야 한다.
  • const마다 iota가 새로 생성된다.

생략법

const (
        a = iota
        b
        c
    )

출력값
0
1
2

응용 0

const (
        zero = "zero"	// zero
        one = iota	// 1
        two = "two"	// two
        three = iota	// 3
    )
  • 상수 const에서 첫 번째 선언부터 0이 카운트 된다.
    즉 zero부터 0

응용 1

const (
        mutexLocked = 1 << iota
        mutexWoken		// 1 << 1
        mutexStarving	// 1 << 2
        mutexWaiterShift = iota
    )

출력값
1
2
4
3

  • shift 연산을 사용.
  • builtIn sync.Mutex 코드 참고.

응용 2

const (
        zero = iota * iota
        one			
        two			
        three		
    )

출력값
0
1
4
9

  • 연산도 가능하다.

대입 우선

const (
        iota = 0	// iota
        zero = iota	// iota
        one		// iota
        two		// iota
        three		// iota
    )

출력값
0
0
0
0

  • iota를 초기화 하는 경우 자동 increment가 사라진다.
  • 문자열로 초기화 하는 경우 (예. iota="iota") "iota"가 출력이 된다.

0개의 댓글