Swift: what's a use case for passing a primitive by reference [duplicate] - arguments

This question already has an answer here:
Does Swift have something like "ref" keyword that forces parameter to be passed by reference?
(1 answer)
Closed 8 years ago.
Swift has the inout keyword to pass a primitive argument by reference. When would I use this over just passing it by value?
Edit: I realize that you can use this to change its value, but why not just pass it by value and assign it the corresponding value in the tuple returned by the function?

You would do that if you wanted to modify the original value instead of just a copy. However, I would argue that you should just return the new value since you can return multiple values in Swift.

This seems to be a plausible reason:
"Maybe the existing body of Objective C libraries have a lot of out parameters, and they didn't want to wrap them all for Swift."
http://blog.lexspoon.org/2014/06/my-analysis-of-swift-language.html

Related

Golang: The differences between these two ways of initializing struct [duplicate]

This question already has answers here:
When to use pointers [duplicate]
(1 answer)
I don't understand when to use pointers on go [duplicate]
(2 answers)
Difference between returning a pointer and a value in initialization methods [duplicate]
(1 answer)
Pointers vs. values in parameters and return values
(5 answers)
Golang struct initialization
(2 answers)
Closed 15 days ago.
I am wondering what the differences are between those two ways of initializing a struct in Go. Does the second one give you a pointer storing the address of the struct? But they have the same syntax if we want to change the field variables, so how are they different?
I can de-reference the pointer, apparently. But do they have different functionalities? In what scenario would I prefer one over the other?
b := Student{Name:"Bob"}
pb := &Student{Name:"Bob", Age:8,}
They only differ in what the type of the local variable is. Whether to prefer one over the other depends entirely on how you would use that variable in the remainder of the function's body. If you are always passing it around (meaning use it on the right-hand side of an assignment, as an argument to a function call, or returning it) as a pointer, use the pb := &Student{...} form. If you intend to create (shallow) copies of it, the b := Student{...} form might be more convenient. This is however purely based on the fact that typing pb is easier than &b, and that typing b is easier than *pb. If you apply these substitutions everywhere (except for in the context of field accesses, where it is allowed but not mandatory, see below), they are completely interchangeable.
If you want to be able to set the variable holding the struct (pointer) to nil, use a pointer, obviously. But this can also be solved by introducing a new, pointer-typed variable and setting that to either nil or &b.
Some types in Go cannot be copied (this is typically accomplished by embedding a [0]sync.Mutex field in the struct, which takes up no space but triggers the "mutex copy" error of the compiler). An example would be protobuf structs. For these, it is almost always preferable to use the pointer form; however, this is not required, as the initialization via b := Student{...} is not a copy.
Go allows transparently dereferencing when accessing struct fields. b.Name, (&b).Name, pb.Name, (*pb).Name all work and are equivalent. Note however that transparent dereferencing only works over one level, (&pb).Name will result in a compiler error.
The composite literals differ in the initialization of the Age field. The first sets the field to the zero value. The second sets the field to the number 8. Otherwise, the initialization of the struct values is identical.
What happens next is where the key difference lies. The first example assigns the value to a variable named b. The second example takes assigns the value to an anonymous variable; takes the address of the variable; and assigns the result to a variable named pb.
The type of b is the struct type and the type of pb is a pointer to the struct type.
See I don't understand when to use pointers on go to see a discussion on why one might want to use a pointer.

what is difference between *[] *types.a and [] *types.b in golang [duplicate]

This question already has answers here:
Please explain &, and * pointers
(6 answers)
Is it correct to use slice as *[]Item, because Slice is by default pointer
(1 answer)
Closed 4 months ago.
while looking into code I found below function declaration
func (c *Congress) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs *[]*types.Transaction, uncles []*types.Header, receipts *[]*types.Receipt, systemTxs []*types.Transaction) error {
where two parameters are txs *[]*types.Transaction, uncles []*types.Header, what does it mean in terms of golang
just want to understand golang terminology with reference to above code
uncles []*types.Header
uncles is slice. If you copy it somewhere (perhaps by passing it in as a function parameter) updates to it will not propagate backwards to the original (with the nuance that changes to elements will propagate, but the size/data pointer of the original will remain unchanged).
txs *[]*types.Transaction
txs is a pointer to a slice. It’s sort of like a “reference” in that updates to the slice pointed at propagate to anyone else pointing to that slice. So if you pass a pointer to a slice as a function parameter, the function may change the properties of the slice pointed to (adding/removing elements).

What does a pair of round brackets syntax expression mean in Go? [duplicate]

This question already has answers here:
Typecasting in Golang
(5 answers)
Closed 2 years ago.
Reading this https://github.com/go-pg/pg/wiki/Writing-Queries#select I see many times this expression:
(*Book)(nil)
Example:
count, err := db.Model((*Book)(nil)).Count()
What does it mean?
That is a type conversion. Assuming the db.Model function takes interface{}, it sends an nil interface of type *Book to the function.
To convert a value v to type Book, you'd write:
Book(v)
However, you cannot write Book(nil) because nil is a pointer and Book is not. If you had a type
type BookPtr *Book
Then you could've written BookPtr(nil). Extending that, you want to write *Book(nil), but that means *(Book(nil)) which is invalid, hence:
(*Book)(nil)
'nil' is to Go what NULL/null is to other languages like C#/Java, etc. The *Variable is just getting the pointer value for the Book object of Model.
So in this case, I believe what's happening here is that (*Book)(nil) is setting the pointer value of the Book object of the Model to nil(/null).
Hope this helps in some way. 😊
Good Resource: https://go101.org/article/nil.html

Why is there formal parameter type in static method Stream.empty() although there is no parameter in the method? [duplicate]

This question already has answers here:
Explain the syntax of Collections.<String>emptyList()
(5 answers)
Closed 5 years ago.
Formal parameter type is allowed in Java 8 and, it is usually used when there are parameters with generic types AFAIK.
However, there are indeed some methods without parameters but formal parameter type anyway. For instance,
<T> Stream<T> java.util.stream.Stream.empty()
Anyone can explain on this?
The generic type argument is required here to specify the element type of the returned empty Stream. Otherwise this method would return a raw Stream type.
For example:
Stream<String> stream = Stream.empty();

Unable to update Kotlin method parameter's value [duplicate]

This question already has answers here:
Kotlin function parameter: Val cannot be reassigned
(4 answers)
Closed 5 years ago.
I've following Kotlin method
fun getpower(base:Int,power:Int):Int
{
var result = 1
while(power > 0){
result = result * base
power-- // <---- error in this line
}
return result
}
Kotlin compiler gives following error
Error:(6, 8) Val cannot be reassigned
What's wrong with updating the variable?
What's wrong with updating the variable?
The others answer the question by effectively saying "because Kotlin function parameters are immutable." Of course, that is a(the) correct answer.
But given the fact so many languages, including Java, allow you to re-assign function parameters, it might be valid to interpret your question as "why does Kotlin disallow re-assigning function parameters?"
My Answer: Kotlin and Swift have many features in common, so I went to Swift 3 to see why they decided to deprecate function parameter re-assignment and found this motivation.
Using var annotations on function parameters have limited utility, optimizing for a line of code at the cost of confusion with inout , which has the semantics most people expect. To emphasize the fact these values are unique copies and don't have the write-back semantics of inout , we should not allow var here.
In summary, the problems that motivate this change are:
• var is often confused with inout in function parameters.
• var is often confused to make value types have reference semantics.
•Function parameters are not refutable patterns like in if-, while-, guard-, for-in-, and case statements.
Of course, Kotlin has no inout decoration. But the writers could have chosen to allow val and var, with val being the default. Then they would have had behavior consistent with many other languages. Instead, they opted for code clarity.
The OPs example code shows a valid example of when parameter re-assignment is clear and natural. Having to add one more line to a very short function (to get a local variable to do what the parameter variable could have done) IMHO reduces clarity. Again, IMHO, I would have preferred optionally being able to declare my parameters as var.
A function's parameters inside the function are read-only (like variables created with val), therefore they cannot be reassigned.
You can see discussions about this design decision here and here.
In Kotlin, method parameter's are val(non-mutable) type not var(mutable) type. Similar as java final.
That's why i cant mutate(change) that .
The error you saw has more to do with scoping. A function's parameter by design is immutable or more accurately, read-only and that is what the val keyword stands for that is why you see that error.

Resources