问题
C# warns for unused variables that are compile-time constants:
static void Main(string[] args)
{
var unused = "hey"; //CS0219 The variable 'unused' is assigned but its value is never used
Console.WriteLine("Hello World!");
}
But the F# compiler does not, even though the editor now does pick it up:
If it covered not just compile-time constants but all let bindings, this would have caught a real bug in production caused by a trivial mistake, something like
let callApiXyz connectionInfo = async {
let fullUrl = sprintf "%s..." connectionInfo.Url
...
let! result = httpGet connectionInfo // fail, didn't use the modified url
// Should have been:
// let! result = httpGet { connectionInfo with Url = fullUrl }
...
}
Is there any reason not to have this (other than "features are not free")? I feel this should be more important in a functional-first language where expressions tend not to have side-effects, than in C#.
回答1:
You can enable warning for unused bindings via the warnon
compiler option. If you want to be strict, you can even use warnaserror+
to turn it into an error.
The warning number is 1182 and it is turned off by default as documented in the compiler options page in the F# documentation.
fsc --warnaserror+:1182 --warnon:1182 Program.fs
How to do this will depend on your editor. In Visual Studio, you can do this by specifying "Other flags" and "Treat warnings as errors" in project properties.
回答2:
For those of us that don't have Visual Studio and edit the fsproj by hand, the way to implement Tomas's answer is
<PropertyGroup>
<OtherFlags>$(OtherFlags) --warnon:1182</OtherFlags>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
As an example, see the project file of FSharp.Core itself.
来源:https://stackoverflow.com/questions/49199913/why-no-warning-for-unused-let-bindings