This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Style Guide
Gav Wood edited this page Jul 5, 2018
·
20 revisions
- Indent using tabs
- Never have spaces on a line prior to a non-whitespace character
- Follow-on lines are only ever a single indent from the original line.
fn long_simple_calculation(some_long_variable_a: i8, some_long_variable_b: i8) -> bool {
let x = some_long_variable_a * some_long_variable_b
- some_long_variable_b / some_long_variable_a
+ sqrt(some_long_variable_a) - sqrt(some_long_variable_b);
x > 10
}
- Indent level should follow open parens/brackets, but should be collapsed to the smallest number of levels actually used:
fn calculate(some_long_variable_a: f32, some_long_variable_b: f32, some_long_variable_c: f32) -> f32 {
(-some_long_variable_b + sqrt(
// two parens open, but since we open & close them both on the same
// line, only one indent level is used
some_long_variable_b * some_long_variable_b
- 4 * some_long_variable_a * some_long_variable_c
// both closed here at beginning of line, so back to the original indent level
)) / (2 * some_long_variable_a)
}
-
where
is indented, and its items are indented one further - Long arg lists or function calls are indented similarly to code blocks, and once one param is indented in such a way, all others should be, too. Run-on parameter lists are also acceptable for single-line run-ons of basic function calls.
fn foo(
really_long_parameter_name_1: SomeLongTypeName,
really_long_parameter_name_2: SomeLongTypeName,
shrt_nm_1: u8,
shrt_nm_2: u8
) {
// Complex line (not just a function call, also a let statement). Full structure.
let (a, b) = bar(
really_long_parameter_name_1,
really_long_parameter_name_2,
shrt_nm_1,
shrt_nm_2,
);
// Long, simple function call that fits onto two lines. Inline with a run-on.
waz(really_long_parameter_name_1, really_long_parameter_name_2,
shrt_nm_1, shrt_nm_2);
// Short function call. Inline.
baz(a, b);
}
- Always end last item of a multi-line comma-delimited set with
,
when legal:
struct Point<T> {
x: T,
y: T, // <-- Multiline comma-delimited lists end with a trailing ,
}
// Single line comma-delimited items do not have a trailing `,`
enum Meal { Breakfast, Lunch, Dinner };
- Avoid trailing
;
s where unneeded.
if condition {
return 1 // <-- no ; here
}
-
match
arms may be either blocks or have a trailing,
but not both. - Blocks should not be used unnecessarily.
match meal {
Meal::Breakfast => "eggs",
Meal::Lunch => { check_diet(); recipe() }
// Meal::Dinner => { return Err("Fasting") } // WRONG
Meal::Dinner => return Err("Fasting"),
}