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:
github-actions[bot] 2025-03-19 14:46:55 +00:00 committed by GitHub
parent ef35f53a80
commit 2713aeaed6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 83 additions and 1 deletions

View File

@ -30,4 +30,4 @@
"js",
"ts"
]
}
}

View File

@ -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"
}

View File

@ -0,0 +1,9 @@
{
"title": "Field init shorthand should be used",
"tags": [
"clippy"
],
"defaultQualityProfiles": [
"Sonar way"
]
}

View 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