Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature request] Return by let/const value (Apply parameter constraints to return values) #6793

Closed
mratsim opened this issue Nov 24, 2017 · 4 comments
Labels

Comments

@mratsim
Copy link
Collaborator

mratsim commented Nov 24, 2017

I would like have something similar to C++ const return value so that the compiler statically ensure that the result of a proc is only used in a non-mutable context.

Assuming we use the parameter constraints syntax I would like this to not compile:

proc foo[T](s: seq[T]): seq[T]{`let`, call} =
  shallowCopy(result, s)

let x = @[1, 2, 3]

var y = foo(x)

This way we can have specialization depending on how the result will be used.

proc foo[T](s: seq[T]{`let`, call}): seq[T]{`let`, call} =
  shallowCopy(result, s)

proc foo[T](s: seq[T]): seq[T] =
  result = s

let x = @[1, 2, 3]

var y = foo(x) # deep copy
let z = foo(x).bar() # bar will receive a shallowCopy (similar to what is possible today with parameter constraints
let a = foo(x) # a will receive a shallowCopy

In my opinion the big advantage is when working with read-only slices of big objects.

Note: I tried to make that work with term rewriting macro, you can catch:

var y: seq[int]
y = foo(x)

but not var y = foo(x)

@Araq
Copy link
Member

Araq commented Nov 24, 2017

proc foo(s: T): T{`let`, call} =
  shallowCopy(result, s)

proc main =
  let x = foo("some input of type T")
  var s: seq[T] = @[]
  for i in 0 ..< 100:
    s.add x # shallowCopy here? or full copy?

How do you track lifetimes with your idea? If shallow copies are fine, why is var so bad? I can create a copy without var easily.

@mratsim
Copy link
Collaborator Author

mratsim commented Nov 24, 2017 via email

@metagn
Copy link
Collaborator

metagn commented Nov 23, 2021

Does lent solve this?

@Araq
Copy link
Member

Araq commented Aug 27, 2023

Seems to describe lent T indeed.

@Araq Araq closed this as completed Aug 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants