golang 기초 - 맵

한나리·2023년 6월 26일

Go

목록 보기
5/19
post-thumbnail

키와 값 형태로 데이터를 한쌍으로 저장하는 자료구조
맵은 순서가 보장되지 않음

// 맵
var numMap = map[string]int {
	"one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}
// 맵
var numMap = make(map[string]int) //map[키]값
	numMap["one"] = 1,
    numMap["two"] = 2,
    numMap["three"] = 3,
    numMap["four"] = 4,

package main

import (
	"fmt"
)

func main() {

var numMap = make(map[string]int) 
	numMap["one"] = 1,
    numMap["two"] = 2,
    numMap["three"] = 3,
    
    
    fmt.Println(numMap) // map[one: 1 three:3 two:2] 맵은 순서가 없음
    fmt.Println(numMap["one"]) //1
    fmt.Println(numMap["two"]) //2
    fmt.Println(numMap["three"]) //3
}    

맵 명령어

//맵 선언
var numMap = make(map[string]int)

//요소 추가
numMap["one"] = 1

//요소 접근
fmt.Println(numMap["one"])

//요소 제거
delete(numMap, "one")

//요소 존재 체크
value, isKey := numMap["one"]
fmt.Println(value, isKey)

package main

import (
	"fmt"
)

func main() {

var numMap = make(map[string]int) 
	numMap["one"] = 1,
    numMap["two"] = 2,
    numMap["three"] = 3,
    
	value, isKey := numMap["one"]
	fmt.Println(value, isKey) // 1 true
    
    value, isKey := numMap["four"]
	fmt.Println(value, isKey) // 0 false
    
    delete(numMap, "two")
     value, isKey := numMap["two"]
	fmt.Println(value, isKey) // 0 false
    
}    
profile
내가 떠나기 전까지는 망하지 마라, 블록체인 개발자

0개의 댓글