• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang slice.Sort函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/bradfitz/slice.Sort函数的典型用法代码示例。如果您正苦于以下问题:Golang Sort函数的具体用法?Golang Sort怎么用?Golang Sort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Sort函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Sort

// Sort chronologically sorts a resume's work and volunteer experience items.
func (rsm *Resume) Sort() {
	slice.Sort(rsm.Work, func(i, j int) bool {
		return rsm.Work[i].StartDate.Before(rsm.Work[j].StartDate.Time)
	})

	slice.Sort(rsm.Volunteer, func(i, j int) bool {
		return rsm.Volunteer[i].StartDate.Before(rsm.Volunteer[j].StartDate.Time)
	})
}
开发者ID:james-relyea,项目名称:dresh,代码行数:10,代码来源:resume.go


示例2: GetNotification

func GetNotification(c web.C, w http.ResponseWriter, r *http.Request) {
	var token = r.FormValue("token")
	var userId int

	//init my empty struct who contains an array string for login user
	notifs := Notifications{}

	//check if token exist
	if CheckToken(token, w) == false {
		return
	}
	//check if token matches with an user Id
	if userId = GetUserIdWithToken(token, w); userId == -1 {
		return
	}
	a := MyAppend(GetMessageNotification(userId), GetLikeNotification(userId))
	notifs.Notif = MyAppend(a, GetVisiteNotification(userId))

	slice.Sort(notifs.Notif[:], func(i, j int) bool {
		if strings.Compare(notifs.Notif[i].CreateAt, notifs.Notif[j].CreateAt) > 0 {
			return true
		} else {
			return false
		}
	})

	notifs.Status = "OK"
	go MakeNotifAsRead(userId)
	RenderJSON(w, notifs, http.StatusOK)
}
开发者ID:Fantasim,项目名称:Langage-Go,代码行数:30,代码来源:notifications.go


示例3: makeChart

func makeChart(r opentsdb.ResponseSet, m_units map[string]string) ([]*chartSeries, error) {
	var series []*chartSeries
	for _, resp := range r {
		dps := make([][2]float64, 0)
		for k, v := range resp.DPS {
			ki, err := strconv.ParseInt(k, 10, 64)
			if err != nil {
				return nil, err
			}
			dps = append(dps, [2]float64{float64(ki), float64(v)})
		}
		if len(dps) > 0 {
			slice.Sort(dps, func(i, j int) bool {
				return dps[i][0] < dps[j][0]
			})
			name := resp.Metric
			if len(resp.Tags) > 0 {
				name += resp.Tags.String()
			}
			series = append(series, &chartSeries{
				Name:   name,
				Metric: resp.Metric,
				Tags:   resp.Tags,
				Data:   dps,
				Unit:   m_units[resp.Metric],
			})
		}
	}
	return series, nil
}
开发者ID:nicollet,项目名称:bosun,代码行数:30,代码来源:chart.go


示例4: SortByCounter

// SortByCounter sorts the list by the counter of the word
func (digester *Digester) SortByCounter(order string) {
	data := digester.GetData()
	slice.Sort(data, func(i, j int) bool {
		if order == "ASC" {
			return data[i].GetCounter() <= data[j].GetCounter()
		}
		return data[i].GetCounter() > data[j].GetCounter()
	})
}
开发者ID:cristian-sima,项目名称:Wisply,代码行数:10,代码来源:digester.go


示例5: BenchmarkIntSlice

func BenchmarkIntSlice(b *testing.B) {
	s := make([]int, len(intdata))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		copy(s, intdata)
		slice.Sort(s, func(i, j int) bool {
			return s[i] > s[j]
		})
	}
}
开发者ID:pat42smith,项目名称:relax,代码行数:10,代码来源:sort_benchmark_test.go


示例6: BenchmarkStringSlice

func BenchmarkStringSlice(b *testing.B) {
	s := make([]string, len(strdata))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		copy(s, strdata)
		slice.Sort(s, func(i, j int) bool {
			return s[i] > s[j]
		})
	}
}
开发者ID:pat42smith,项目名称:relax,代码行数:10,代码来源:sort_benchmark_test.go


示例7: String

func (r Route) String() string {
	rt := []string{}
	for _, part := range r.parts {
		rt = append(rt, part.String())
	}
	slice.Sort(rt, func(i, j int) bool {
		return rt[i] < rt[j]
	})
	return fmt.Sprintf("Route(%s)", strings.Join(rt, " && "))
}
开发者ID:albertrdixon,项目名称:romulus,代码行数:10,代码来源:types.go


示例8: getLastNotification

func (notification *Notification) getLastNotification() SimpleNotificationList {
	v := GroupedList{}
	ret := SimpleNotificationList{}

	lastWeek := time.Now().AddDate(0, 0, -7)
	//Get from database all notification between now and a week ago, we group them by type and IdLink
	curs, _ := r.Table("notifications").
		Filter(r.Row.Field("UserId").Eq(notification.user.Id)).
		Filter(r.Row.Field("CreatedAt").Gt(lastWeek)).
		OrderBy("-CreatedAt").
		Group("Type", "IdLink").
		Run(api.Sess)
	curs.All(&v.List)

	//We sort all notification to avoid had identic notifications.

	var arraySimpleNotification []SimpleNotification
	for _, group := range v.List {

		simple := SimpleNotification{
			Type:   group.Group[0].(string),
			IdLink: group.Group[1].(string),
			Read:   true,
		}
		var create time.Time
		var index = -1
		for j, notif := range group.Reduction {

			if notif.Read == false {
				simple.Read = false
			}
			if create.Before(notif.CreatedAt) == true {
				create = notif.CreatedAt
				index = j
			}
		}
		simple.CreatedAt = create
		simple.Name = group.Reduction[index].Name
		simple.Others = len(group.Reduction) - 1
		arraySimpleNotification = append(arraySimpleNotification, simple)
	}
	//Sort by createDate
	slice.Sort(arraySimpleNotification[:], func(i, j int) bool {
		return arraySimpleNotification[i].CreatedAt.After(arraySimpleNotification[j].CreatedAt)
	})

	ret.List = arraySimpleNotification
	return ret
}
开发者ID:Fantasim,项目名称:Langage-Go,代码行数:49,代码来源:lib.go


示例9: cmdSummary

func cmdSummary(d db.DB, periodS, firstDayS string) {
	period, err := datetime.ParsePeriod(periodS)
	if err != nil {
		fatal(err)
	}
	firstDay, err := datetime.ParseWeekday(firstDayS)
	if err != nil {
		fatal(err)
	}
	categories, err := d.Categories()
	if err != nil {
		fatal(err)
	}
	itr, err := NewSummaryIterator(d, period, firstDay, time.Now())
	if err != nil {
		fatal(err)
	}
	defer itr.Close()
	for {
		if summary, err := itr.Next(); err == io.EOF {
			break
		} else if err != nil {
			fatal(err)
		} else {
			fmt.Printf("%s\n\n", PeriodHeadline(summary.From, summary.To, period))
			names := make(map[string]string)
			order := make([]string, 0, len(summary.Categories))
			for id, _ := range summary.Categories {
				names[id] = FormatCategory(categories.Path(id))
				order = append(order, id)
			}
			slice.Sort(order, func(i, j int) bool {
				return summary.Categories[order[i]] > summary.Categories[order[j]]
			})
			t := table.New().Padding(" ")
			for _, id := range order {
				d := FormatDuration(summary.Categories[id])
				t.Add(table.String(names[id]), table.String(d).Align(table.Right))
			}
			fmt.Printf("%s\n", Indent(t.String(), "  "))
		}
	}
}
开发者ID:hiroapp,项目名称:cli,代码行数:43,代码来源:cmds.go


示例10: Available

// Available return the migrations in the environment's directory sorted in
// ascending lexicographic order.
func (s Service) Available() ([]*Migration, error) {
	files, _ := filepath.Glob(filepath.Join(s.env.Directory, "*.sql")) // The only possible error here is a pattern error

	var migrations []*Migration
	for _, file := range files {
		migration, err := NewMigration(file)
		if err != nil {
			return nil, err
		}

		migrations = append(migrations, migration)
	}

	slice.Sort(migrations, func(i, j int) bool {
		return migrations[i].Name < migrations[j].Name
	})

	return migrations, nil
}
开发者ID:shawndellysse,项目名称:rambler,代码行数:21,代码来源:service.go


示例11: Root

// Tree returns the root node of the category tree.
func (c CategoryMap) Root() *CategoryNode {
	index := map[string]*CategoryNode{"": &CategoryNode{}}
	for _, category := range c {
		parent := index[category.ParentID]
		if parent == nil {
			parent = &CategoryNode{}
			index[category.ParentID] = parent
		}
		node := index[category.ID]
		if node == nil {
			node = &CategoryNode{}
			index[category.ID] = node
		}
		node.Category = category
		parent.Children = append(parent.Children, node)
		slice.Sort(parent.Children, func(i, j int) bool {
			return parent.Children[i].Name < parent.Children[j].Name
		})
	}
	return index[""]
}
开发者ID:hiroapp,项目名称:cli,代码行数:22,代码来源:models.go


示例12: ExprGraph

func (s *Schedule) ExprGraph(t miniprofiler.Timer, unit string, res []*expr.Result) (chart.Chart, error) {
	c := chart.ScatterChart{
		Key:    chart.Key{Pos: "itl"},
		YRange: chart.Range{Label: unit},
	}
	c.XRange.Time = true
	for ri, r := range res {
		rv := r.Value.(expr.Series)
		pts := make([]chart.EPoint, len(rv))
		idx := 0
		for k, v := range rv {
			pts[idx].X = float64(k.Unix())
			pts[idx].Y = v
			idx++
		}
		slice.Sort(pts, func(i, j int) bool {
			return pts[i].X < pts[j].X
		})
		c.AddData(r.Group.String(), pts, chart.PlotStyleLinesPoints, Autostyle(ri))
	}
	return &c, nil
}
开发者ID:noblehng,项目名称:bosun,代码行数:22,代码来源:chart.go


示例13: Applied

// Applied return the migrations in the environment's directory that are marked
// as applied in the database sorted in ascending lexicographic order.
func (s Service) Applied() ([]*Migration, error) {
	files, err := s.conn.GetApplied()
	if err != nil {
		return nil, err
	}

	var migrations []*Migration
	for _, file := range files {
		migration, err := NewMigration(filepath.Join(s.env.Directory, file))
		if err != nil {
			return nil, err
		}

		migrations = append(migrations, migration)
	}

	slice.Sort(migrations, func(i, j int) bool {
		return migrations[i].Name < migrations[j].Name
	})

	return migrations, nil
}
开发者ID:shawndellysse,项目名称:rambler,代码行数:24,代码来源:service.go


示例14: getNearestPoints

// GET /points/nearest?lat=*&lng=*&dist=_
func getNearestPoints(w http.ResponseWriter, r *http.Request) {
	badRequestError := Response{"error", 400, "Bad Request", nil}
	params := r.URL.Query()

	lat, err1 := strconv.ParseFloat(params.Get("lat"), 64)
	lng, err2 := strconv.ParseFloat(params.Get("lng"), 64)

	if err1 != nil || err2 != nil {
		routes.ServeJson(w, badRequestError)
		return
	}

	maxDistance := float64(50)
	if d, err := strconv.ParseFloat(params.Get("dist"), 32); err == nil {
		maxDistance = d
	}

	currentPoint := geo.NewPoint(lat, lng)

	var p Point
	result := make([]distanceRecord, 0)
	iter := Points.Find(bson.M{}).Iter()
	for iter.Next(&p) {
		lat, _ := strconv.ParseFloat(p.Latitude, 64)
		lng, _ := strconv.ParseFloat(p.Longitude, 64)

		point := geo.NewPoint(lat, lng)
		distance := currentPoint.GreatCircleDistance(point) * 1000

		if distance <= maxDistance {
			result = append(result, distanceRecord{p.Id, distance})
		}
	}

	slice.Sort(result, func(i, j int) bool {
		return result[i].Distance < result[j].Distance
	})
	routes.ServeJson(w, result)
}
开发者ID:the-varlog,项目名称:wego,代码行数:40,代码来源:points.go


示例15: GatherStats

func GatherStats(config models.Configuration) (stats []models.Status) {
	stats = []models.Status{}
	for _, server := range config.Servers {
		pingSuccess := testPing(server.Hostname, false, config)

		var httpSuccess bool
		if server.Url != "" {
			httpSuccess = testHttp(server.Url, config)
		}

		status := models.Status{
			Name:        server.Name,
			HttpPresent: server.Url != "",
			HttpSuccess: httpSuccess,
			PingSuccess: pingSuccess,
			Created:     time.Now(),
		}
		stats = append(stats, status)
	}
	slice.Sort(stats[:], func(i, j int) bool {
		return stats[i].Name < stats[j].Name
	})
	return stats
}
开发者ID:phantomdata,项目名称:go-status,代码行数:24,代码来源:stats.go


示例16: Graph


//.........这里部分代码省略.........
			if meta.Unit != "" {
				m_units[q.Metric] = meta.Unit
			}
			if meta.Rate != "" {
				switch meta.Rate {
				case metadata.Gauge:
					// ignore
				case metadata.Rate:
					q.Rate = true
				case metadata.Counter:
					q.Rate = true
					q.RateOptions = opentsdb.RateOptions{
						Counter:    true,
						ResetValue: 1,
					}
				default:
					return nil, fmt.Errorf("unknown metadata rate: %s", meta.Rate)
				}
			}
		}
		queries[i] = fmt.Sprintf(`q("%v", "%v", "%v")`, q, start, end)
		if !schedule.SystemConf.GetTSDBContext().Version().FilterSupport() {
			if err := schedule.Search.Expand(q); err != nil {
				return nil, err
			}
		}
	}
	var tr opentsdb.ResponseSet
	b, _ := json.MarshalIndent(oreq, "", "  ")
	t.StepCustomTiming("tsdb", "query", string(b), func() {
		h := schedule.SystemConf.GetTSDBHost()
		if h == "" {
			err = fmt.Errorf("tsdbHost not set")
			return
		}
		tr, err = oreq.Query(h)
	})
	if err != nil {
		return nil, err
	}
	cs, err := makeChart(tr, m_units)
	if err != nil {
		return nil, err
	}
	if _, present := r.Form["png"]; present {
		c := chart.ScatterChart{
			Title: fmt.Sprintf("%v - %v", oreq.Start, queries),
		}
		c.XRange.Time = true
		if min, err := strconv.ParseFloat(r.FormValue("min"), 64); err == nil {
			c.YRange.MinMode.Fixed = true
			c.YRange.MinMode.Value = min
		}
		if max, err := strconv.ParseFloat(r.FormValue("max"), 64); err == nil {
			c.YRange.MaxMode.Fixed = true
			c.YRange.MaxMode.Value = max
		}
		for ri, r := range cs {
			pts := make([]chart.EPoint, len(r.Data))
			for idx, v := range r.Data {
				pts[idx].X = v[0]
				pts[idx].Y = v[1]
			}
			slice.Sort(pts, func(i, j int) bool {
				return pts[i].X < pts[j].X
			})
			c.AddData(r.Name, pts, chart.PlotStyleLinesPoints, sched.Autostyle(ri))
		}
		w.Header().Set("Content-Type", "image/svg+xml")
		white := color.RGBA{0xff, 0xff, 0xff, 0xff}
		const width = 800
		const height = 600
		s := svg.New(w)
		s.Start(width, height)
		s.Rect(0, 0, width, height, "fill: #ffffff")
		sgr := svgg.AddTo(s, 0, 0, width, height, "", 12, white)
		c.Plot(sgr)
		s.End()
		return nil, nil
	}
	var a []annotate.Annotation
	warnings := []string{}
	if schedule.SystemConf.AnnotateEnabled() {
		a, err = annotateBackend.GetAnnotations(&startT, &endT)
		if err != nil {
			warnings = append(warnings, fmt.Sprintf("unable to get annotations: %v", err))
		}
	}
	return struct {
		Queries     []string
		Series      []*chartSeries
		Annotations []annotate.Annotation
		Warnings    []string
	}{
		queries,
		cs,
		a,
		warnings,
	}, nil
}
开发者ID:nicollet,项目名称:bosun,代码行数:101,代码来源:chart.go


示例17: reverse

func reverse(service Servicer, all bool) error {
	initialized, err := service.Initialized()
	if err != nil {
		return fmt.Errorf("unable to check for database state: %s", err)
	}

	if !initialized {
		return fmt.Errorf("uninitialized database")
	}

	available, err := service.Available()
	if err != nil {
		return fmt.Errorf("unable to retrieve available migrations: %s", err)
	}

	applied, err := service.Applied()
	if err != nil {
		return fmt.Errorf("unable to retrieve applied migrations: %s", err)
	}

	if len(applied) == 0 {
		return nil
	}

	var i, j = len(available) - 1, len(applied) - 1
	for i >= 0 && j >= 0 && available[i].Name > applied[j].Name {
		i--
	}

	for i >= 0 && j >= 0 {
		if available[i].Name == applied[j].Name {
			i--
			j--
			continue
		}

		if available[i].Name < applied[j].Name {
			return fmt.Errorf("missing migration: %s", applied[j].Name)
		}

		if available[i].Name > applied[j].Name {
			return fmt.Errorf("out of order migration: %s", available[i].Name)
		}
	}

	if i >= 0 {
		return fmt.Errorf("out of order migration: %s", available[i].Name)
	}

	if j >= 0 {
		return fmt.Errorf("missing migration: %s", applied[j].Name)
	}

	slice.Sort(applied, func(i, j int) bool {
		return applied[i].Name > applied[j].Name
	})

	for _, migration := range applied {
		err := service.Reverse(migration)
		if err != nil {
			return err
		}

		if !all {
			return nil
		}
	}

	return nil
}
开发者ID:rsterbin,项目名称:rambler,代码行数:70,代码来源:reverse.go


示例18: MarshalGroups


//.........这里部分代码省略.........
				if err2 = s.ActionByAlertKey("bosun", "closing because alert doesn't exist.", models.ActionForceClose, k); err2 != nil {
					slog.Error(err2)
				}
				continue
			}
			is, err2 := MakeIncidentSummary(s.RuleConf, silenced, v)
			if err2 != nil {
				err = err2
				return
			}
			match := false
			match, err2 = boolq.AskParsedExpr(parsedExpr, is)
			if err2 != nil {
				err = err2
				return
			}
			if match {
				status[k] = v
			}
		}
	})
	if err != nil {
		return nil, err
	}
	T.Step("GroupStates", func(T miniprofiler.Timer) {
		groups = status.GroupStates(silenced)
	})
	T.Step("groups", func(T miniprofiler.Timer) {
		for tuple, states := range groups {
			var grouped []*StateGroup
			switch tuple.Status {
			case models.StWarning, models.StCritical, models.StUnknown:
				var sets map[string]models.AlertKeys
				T.Step(fmt.Sprintf("GroupSets (%d): %v", len(states), tuple), func(T miniprofiler.Timer) {
					sets = states.GroupSets(s.SystemConf.GetMinGroupSize())
				})
				for name, group := range sets {
					g := StateGroup{
						Active:        tuple.Active,
						Status:        tuple.Status,
						CurrentStatus: tuple.CurrentStatus,
						Silenced:      tuple.Silenced,
						Subject:       fmt.Sprintf("%s - %s", tuple.Status, name),
					}
					for _, ak := range group {
						st := status[ak]
						st.Body = ""
						st.EmailBody = nil
						st.Attachments = nil
						g.Children = append(g.Children, &StateGroup{
							Active:   tuple.Active,
							Status:   tuple.Status,
							Silenced: tuple.Silenced,
							AlertKey: ak,
							Alert:    ak.Name(),
							Subject:  string(st.Subject),
							Ago:      marshalTime(st.Last().Time),
							State:    st,
							IsError:  !s.AlertSuccessful(ak.Name()),
						})
					}
					if len(g.Children) == 1 && g.Children[0].Subject != "" {
						g.Subject = g.Children[0].Subject
					}
					grouped = append(grouped, &g)
				}
			default:
				continue
			}
			if tuple.NeedAck {
				t.Groups.NeedAck = append(t.Groups.NeedAck, grouped...)
			} else {
				t.Groups.Acknowledged = append(t.Groups.Acknowledged, grouped...)
			}
		}
	})
	T.Step("sort", func(T miniprofiler.Timer) {
		gsort := func(grp []*StateGroup) func(i, j int) bool {
			return func(i, j int) bool {
				a := grp[i]
				b := grp[j]
				if a.Active && !b.Active {
					return true
				} else if !a.Active && b.Active {
					return false
				}
				if a.Status != b.Status {
					return a.Status > b.Status
				}
				if a.AlertKey != b.AlertKey {
					return a.AlertKey < b.AlertKey
				}
				return a.Subject < b.Subject
			}
		}
		slice.Sort(t.Groups.NeedAck, gsort(t.Groups.NeedAck))
		slice.Sort(t.Groups.Acknowledged, gsort(t.Groups.Acknowledged))
	})
	return &t, nil
}
开发者ID:nicollet,项目名称:bosun,代码行数:101,代码来源:sched.go


示例19: commands


//.........这里部分代码省略.........
		}
		tick()
	}
	playIdx := func(c cmdPlayIdx) {
		stop()
		srv.PlaylistIndex = int(c)
		play()
	}
	playTrack := func(c cmdPlayTrack) {
		t := SongID(c)
		info, err := srv.getSong(t)
		if err != nil {
			broadcastErr(err)
			return
		}
		album := info.Album
		p, err := srv.getInstance(t.Protocol(), t.Key())
		if err != nil {
			broadcastErr(err)
			return
		}
		list, err := p.List()
		if err != nil {
			broadcastErr(err)
			return
		}
		top := codec.NewID(t.Protocol(), t.Key())
		var ids []codec.ID
		for id, si := range list {
			if si.Album == album {
				ids = append(ids, id)
			}
		}
		slice.Sort(ids, func(i, j int) bool {
			a := list[ids[i]]
			b := list[ids[j]]
			return a.Track < b.Track
		})
		plc := PlaylistChange{[]string{"clear"}}
		for _, v := range ids {
			plc = append(plc, []string{"add", string(top.Push(string(v)))})
		}
		n, _, err := srv.playlistChange(srv.Queue, plc)
		if err != nil {
			broadcastErr(err)
			return
		}
		stop()
		srv.Queue = n
		srv.PlaylistIndex = 0
		for i, s := range srv.Queue {
			if s == t {
				srv.PlaylistIndex = i
			}
		}
		play()
		broadcast(waitPlaylist)
	}
	removeDeleted := func() {
		for n, p := range srv.Playlists {
			p = srv.removeDeleted(p)
			if len(p) == 0 {
				delete(srv.Playlists, n)
			} else {
				srv.Playlists[n] = p
			}
开发者ID:shazow,项目名称:mog,代码行数:67,代码来源:control.go


示例20: Print

// Print the character sheet on the screen
func (c *Character) Print() {
	// Print the name
	fmt.Printf("%s\t%s\n", theme.Title("Name"), c.Name)

	// Print the backgrounds
	backgrounds := []Background{}

	for _, background := range c.Backgrounds {
		backgrounds = append(backgrounds, background)
	}

	slice.Sort(backgrounds, func(i, j int) bool {
		if backgrounds[i].Type != backgrounds[j].Type {
			return backgrounds[i].Type < backgrounds[j].Type
		}

		return backgrounds[i].Name < backgrounds[j].Name
	})

	for _, background := range backgrounds {
		fmt.Printf("%s\t%s\n", theme.Title(strings.Title(background.Type)), strings.Title(background.Name))
	}

	// Print the aptitudes
	aptitudes := []Aptitude{}

	for _, aptitude := range c.Aptitudes {
		aptitudes = append(aptitudes, aptitude)
	}

	slice.Sort(aptitudes, func(i, j int) bool {
		return aptitudes[i] < aptitudes[j]
	})

	fmt.Printf("\n%s (%s)\n", theme.Title("Aptitudes"), theme.Value(fmt.Sprintf("%d", len(aptitudes))))
	for _, aptitude := range aptitudes {
		fmt.Printf("%s\n", strings.Title(string(aptitude)))
	}

	// Print the experience
	fmt.Printf("\n%s\t%d/%d\n", theme.Title("Experience"), c.Spent, c.Experience)

	// Print the characteristics

	var characteristicSum int
	characteristics := []Characteristic{}
	for _, characteristic := range c.Characteristics {
		characteristicSum += characteristic.Value
		characteristics = append(characteristics, characteristic)
	}

	slice.Sort(characteristics, func(i, j int) bool {
		return characteristics[i].Name < characteristics[j].Name
	})

	fmt.Printf("\n%s (%s)\n", theme.Title("Characteristics"), theme.Value(fmt.Sprintf("%d", characteristicSum)))

	for _, characteristic := range characteristics {
		fmt.Printf("%s\t%s %s\n", characteristic.Name, theme.Value(characteristic.Value), theme.Value(characteristic.Level()))
	}

	// Print the gauges

	if len(c.Gauges) != 0 {

		fmt.Printf("\n%s\n", theme.Title("Gauges"))

		gauges := []Gauge{}
		for _, gauge := range c.Gauges {
			gauges = append(gauges, gauge)
		}

		slice.Sort(gauges, func(i, j int) bool {
			return gauges[i].Name < gauges[j].Name
		})

		for _, gauge := range gauges {
			fmt.Printf("%s\t%s\n", gauge.Name, theme.Value(gauge.Value))
		}
	}

	// Print the skills

	if len(c.Skills) != 0 {

		// Print the skills using a tabwriter
		fmt.Printf("\n%s\n", theme.Title("Skills"))

		skills := []Skill{}
		for _, skill := range c.Skills {
			skills = append(skills, skill)
		}

		slice.Sort(skills, func(i, j int) bool {
			return skills[i].FullName() < skills[j].FullName()
		})

		w := tabwriter.NewWriter(os.Stdout, 10, 1, 2, ' ', 0)
		for _, skill := range skills {
//.........这里部分代码省略.........
开发者ID:elwinar,项目名称:adeptus,代码行数:101,代码来源:character.go



注:本文中的github.com/bradfitz/slice.Sort函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang manners.NewWithServer函数代码示例发布时间:2022-05-24
下一篇:
Golang iter.N函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap