Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
example_wrapper_test.go78 linesDownload Raw Back to sort
1// Copyright 2011 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4 5package sort_test6 7import (8	"fmt"9	"sort"10)11 12type Grams int13 14func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }15 16type Organ struct {17	Name   string18	Weight Grams19}20 21type Organs []*Organ22 23func (s Organs) Len() int      { return len(s) }24func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }25 26// ByName implements sort.Interface by providing Less and using the Len and27// Swap methods of the embedded Organs value.28type ByName struct{ Organs }29 30func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }31 32// ByWeight implements sort.Interface by providing Less and using the Len and33// Swap methods of the embedded Organs value.34type ByWeight struct{ Organs }35 36func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }37 38func Example_sortWrapper() {39	s := []*Organ{40		{"brain", 1340},41		{"heart", 290},42		{"liver", 1494},43		{"pancreas", 131},44		{"prostate", 62},45		{"spleen", 162},46	}47 48	sort.Sort(ByWeight{s})49	fmt.Println("Organs by weight:")50	printOrgans(s)51 52	sort.Sort(ByName{s})53	fmt.Println("Organs by name:")54	printOrgans(s)55 56	// Output:57	// Organs by weight:58	// prostate (62g)59	// pancreas (131g)60	// spleen   (162g)61	// heart    (290g)62	// brain    (1340g)63	// liver    (1494g)64	// Organs by name:65	// brain    (1340g)66	// heart    (290g)67	// liver    (1494g)68	// pancreas (131g)69	// prostate (62g)70	// spleen   (162g)71}72 73func printOrgans(s []*Organ) {74	for _, o := range s {75		fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)76	}77}78 
codekingpro/portable-devtools · Team Ai