稳定且确定的输出
Coddy 面向 C# 开发者的 Go 课程的第 17 课,共 48 课。
C# LINQ 的 OrderBy 会返回一个延迟排序的序列,而 Array.Sort 会修改原数据。Go 的 sort.Ints 会立即修改传入的切片。如果调用方需要保留原有顺序,请先复制。
sort.Ints 会修改切片。如果调用方需要保留原数据,请先复制。要以确定的顺序呈现映射,先收集并排序它的键,再按该顺序访问值。字符串的字典序是按字节排序,不是按地区设置进行排序。
C# 示例
using System;
using System.Collections.Generic;
using System.Linq;
class Program { static void Main() {
int[] xs={4,1,3};Console.WriteLine(string.Join(",",xs.OrderByDescending(x=>x)));
} }源代码输出:
4,3,1Go 示例
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,并保留调用方的输入。集合的标准输出使用 Go 的方括号格式,而不是 JSON。
你的代码写在 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)
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Go中的所有课
自己练习: Go 在线编译器