fsharp / fsharp/fslang-suggestions

Disallow "mutable" on byref<'T> locals

Open
#677 8 comments 2 reactions 0 assignees View on GitHub
approved-in-principle area: structs-byrefs-and-span
Dominant language
No language data
Stars
373
Forks
21
PR merge metrics
No merged PRs in 30d

Description

# Disallow "mutable" on byref<'T> locals

Currently, we can write code like this:

```fsharp
let mutable x = 1
let mutable y = &x
y <- 4
```

`y` is of type `byref`. This means we can assign a value to the `byref` as such, `y <- 4`. But, we can do this even if `y` wasn't mutable: `let y = &x; y <- 4`. So what does `mutable` do here? It actually doesn't do anything as making this `mutable` gives intent of assigning byrefs with other byrefs, but we have no way to express that in F# (in fact we may never want to do that in F#). Therefore, `mutable` is moot at this point.

For devs to avoid this confusion, we should never allow `mutable` byref locals, by throwing an error stating that you cannot do this as it serves no purpose. Therefore, the code above should fail to compile. To fix it, write as such:

```fsharp
let mutable x = 1
let y = &x
y <- 4
```

In the future we may or may not to allow assigning byrefs, so it might look like this:

```fsharp
let mutable x = 1
let mutable w = 1
let mutable y = &x
y <- &w
```

But that is not part of this suggestion.

## Pros

Better consistency. Less confusion.

## Cons

This is technically a breaking change, but we think most people do not make this `mutable` because it doesn't do anything.

## Affidavit (please submit!)

Please tick this by placing a cross in the box:
* [x] This is not a question (e.g. like one you might ask on [stackoverflow](http://stackoverflow.com)) and I have searched stackoverflow for discussions of this issue
* [x] I have [searched both open and closed suggestions on this site](http://github.com/fsharp/fslang-suggestions/issues) and believe this is not a duplicate
* [x] This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.

Please tick all that apply:
* [ ] This is not a breaking change to the F# language design
* [x] I or my company would be willing to help implement and/or test this

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.