Menu
CoddyTech

빈 구조체를 사용한 집합

Coddy의 Swift 개발자를 위한 Go 코스 레슨. 48개 중 16번째.

Swift의 Set은 Hashable 요소가 필요하며 값 의미론을 가집니다. Go에서는 보통 map[T]struct{}로 집합을 표현하며 비교 가능한 키가 필요합니다. 해시 가능성과 Go의 비교 가능성은 동일하지 않습니다. 해시 가능한 요소로 이루어진 Swift 배열은 해시 가능할 수 있지만, Go 슬라이스는 맵 키가 될 수 없습니다. 선택한 동등성 모델을 유지하세요.

Go에는 내장 집합 자료형이 없습니다. map[T]struct{}는 별도의 페이로드 없이 멤버십을 표현합니다. 콤마-ok 조회는 멤버십을 확인하고, delete는 키를 제거하며 키가 없어도 안전합니다. 키는 비교 가능한 자료형이어야 합니다.

Swift 예시

var s:Set<String>=["red"]; s.remove("red"); print(s.contains("red"))

Swift 출력:

false

Go 예시

package main
import ("fmt")

func main(){s:=map[string]struct{}{"red":{}}
delete(s,"red")
_,ok:=s["red"]
fmt.Println(ok)}

Go 출력:

false
challenge icon

챌린지

쉬움

쉼표로 구분된 입력 줄에 있는 대소문자를 구분하는 서로 다른 단어의 개수를 반환하세요.

선언된 API를 구현하고, 출력하지 말고 결과를 반환하세요. 드라이버는 필요한 API를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 표준 출력은 JSON이 아닌 Go 대괄호 형식을 사용합니다.

코드는 exercise.go에 작성하세요. main.go에는 제공된 입출력 코드가 있으며 수정할 수 없습니다. 하나의 평면적인 package main을 유지하고, 두 번째 main을 추가하지 마세요.

직접 해보기

package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}

func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=Words(0); before0:=fmt.Sprint(a0)

result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Swift 개발자를 위한 Go의 모든 레슨

직접 연습해 보세요: 온라인 Go 컴파일러