안정적이고 결정적인 출력
Coddy의 Rust 개발자를 위한 Go 코스 레슨. 48개 중 17번째.
Rust 반복자는 소비될 때까지 지연되며, collect는 출력 컬렉션을 선택합니다. Go에서는 일반적으로 명시적인 루프와 append를 사용합니다. Go 슬라이스를 정렬하면 공유 백킹 저장소가 변경되므로, 입력 순서를 보존하려면 먼저 복사하세요. 두 번째 슬라이스 변수만으로 격리되었다고 추론하지 마세요.
sort.Ints는 슬라이스를 수정합니다. 호출자가 원본을 유지하는 경우 먼저 복사하세요. 맵을 결정적으로 렌더링하려면 키를 모아 정렬한 다음, 그 순서대로 값에 접근하세요. 사전식 문자열 순서는 바이트 순서이며, 로캘에 따른 정렬이 아닙니다.
Rust 예시
fn main() {
let words = ["pear", "fig", "plum"];
let mut result: Vec<_> = words.iter().copied().filter(|w| w.len() >= 4).collect();
result.sort_by_key(|w| w.len());
println!("{}", result.join(","));
}소스 출력:
pear,plumGo 예시
package main
import ("fmt";"sort")
func main(){xs:=[]int{4,1,3}
sort.Sort(sort.Reverse(sort.IntSlice(xs)))
fmt.Println(xs)}Go 출력:
[4 3 1]챌린지
쉬움숫자를 오름차순으로 정렬하여 별도의 저장 공간에 반환하세요. 원본 슬라이스의 입력 순서는 보존하세요.
선언된 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:=Ints(0); before0:=fmt.Sprint(a0)
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Rust 개발자를 위한 Go의 모든 레슨
직접 연습해 보세요: 온라인 Go 컴파일러