2.2.1.12 By

12-By — Comprehensive Rust

译文 · 基于 Comprehensive Rust

原文链接: https://google.github.io/comprehensive-rust/idiomatic/foundations-api-design/predictable-api/naming-conventions/by.html

2.2.1.12 By

接受自定义投影或比较函数的方法组成部分。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0
impl<T> [T] {
    fn sort(&mut self) where T: Ord;

    fn sort_by(&mut self, compare: impl FnMut(&T, &T) -> Ordering);

    fn sort_by_key<K, F>(&mut self, f: F)
    where
        F: FnMut(&T) -> K,
        K: Ord;
}
  • sort_by 接受自定义比较器函数,取代正常的 Ord 比较逻辑。

  • sort_by_key 接受投影函数,从原始元素返回用于排序的替代值。这让我们能按结构体的某个字段排序。

  • 有时 “by” 介词只是普通介词:

最后修改 August 11, 2026: 更新 (70a5af133)