Create rule S3498: Field init shorthand should be used (#4727)
* Add rust to rule S3498 * Update RSPEC --------- Co-authored-by: yassin-kammoun-sonarsource <yassin-kammoun-sonarsource@users.noreply.github.com> Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com>
This commit is contained in:
parent
ef35f53a80
commit
2713aeaed6
@ -1,2 +1,35 @@
|
||||
{
|
||||
"title": "Object literal shorthand syntax should be used",
|
||||
"type": "CODE_SMELL",
|
||||
"code": {
|
||||
"impacts": {
|
||||
"MAINTAINABILITY": "LOW"
|
||||
},
|
||||
"attribute": "CONVENTIONAL"
|
||||
},
|
||||
"status": "ready",
|
||||
"remediation": {
|
||||
"func": "Constant\/Issue",
|
||||
"constantCost": "1min"
|
||||
},
|
||||
"tags": [
|
||||
"convention",
|
||||
"es2015"
|
||||
],
|
||||
"extra": {
|
||||
"replacementRules": [
|
||||
|
||||
],
|
||||
"legacyKeys": [
|
||||
|
||||
]
|
||||
},
|
||||
"defaultSeverity": "Minor",
|
||||
"ruleSpecification": "RSPEC-3498",
|
||||
"sqKey": "S3498",
|
||||
"scope": "Main",
|
||||
"defaultQualityProfiles": [
|
||||
|
||||
],
|
||||
"quickfix": "covered"
|
||||
}
|
||||
|
9
rules/S3498/rust/metadata.json
Normal file
9
rules/S3498/rust/metadata.json
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"title": "Field init shorthand should be used",
|
||||
"tags": [
|
||||
"clippy"
|
||||
],
|
||||
"defaultQualityProfiles": [
|
||||
"Sonar way"
|
||||
]
|
||||
}
|
40
rules/S3498/rust/rule.adoc
Normal file
40
rules/S3498/rust/rule.adoc
Normal file
@ -0,0 +1,40 @@
|
||||
== Why is this an issue?
|
||||
|
||||
In Rust, field init shorthand syntax is a more concise way to define fields in structs. It was introduced to make struct initialization more readable and expressive.
|
||||
|
||||
In the shorthand syntax, if a variable exists in the scope with the same name as the struct field you're defining, you can omit the field name and just write the variable name. The compiler will automatically understand that the field and the variable are linked.
|
||||
|
||||
Using field init shorthand syntax can make your code cleaner and easier to read. It can also reduce the chance of making errors, as you don't have to repeat yourself by writing the variable name twice.
|
||||
|
||||
[source,rust,diff-id=1,diff-type=noncompliant]
|
||||
----
|
||||
let a = 1;
|
||||
|
||||
struct MyStruct {
|
||||
a: i32,
|
||||
}
|
||||
|
||||
let my_struct = MyStruct {
|
||||
a: a, // Noncompliant
|
||||
};
|
||||
----
|
||||
|
||||
You can omit the field name and the colon if it is the same as the local variable name.
|
||||
|
||||
[source,rust,diff-id=1,diff-type=compliant]
|
||||
----
|
||||
let a = 1;
|
||||
|
||||
struct MyStruct {
|
||||
a: i32,
|
||||
}
|
||||
|
||||
let my_struct = MyStruct {
|
||||
a,
|
||||
};
|
||||
----
|
||||
|
||||
== Resources
|
||||
=== Documentation
|
||||
|
||||
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#redundant_field_names
|
Loading…
x
Reference in New Issue
Block a user