Difference between big.Int and *big.Int, and how do you pass a big.Int by value - pointers

I can use methods like Text() on a big.Int and it works fine, but if I return a big.Int then use "myfunc().Text()" throws an error, whereas if I return a *big.Int, I get no error. Why can I use Text() on a big.Int, *big.Int, and on a function that returns *big.Int but not on a function whose return value is big.Int?
https://play.golang.org/p/ovgeQDHFstP
Based on this and other behavior (such as how it prints), it seems like *big.Int is the type that is intended for use, is that correct?
Also, if I make and use a variable of type big.Int or *big.Int, it is passed by reference. That's fine. But if I wanted to pass one by value, how is that best done?
Should I make a new big.Int and set it to the original value using Set() and pass that? Or should I pass the original big.Int in, and copy its value to a new big.Int using Set() inside the function? Or is there some other, better way of doing it?

The Text() method is defined for receiver type *big.Int, so obviously you can call it on variables of that type and on return values of functions returning *big.Int. You can also call it on variables of type big.Int, because Go automatically takes the address of a variable when you're trying to call its pointer methods, just to save you the trouble of typing an extra ampersand.
However you can't call it on return value of a function returning big.Int, because that value is not addressable. Here's what the spec says about addressability:
For an operand x of type T, the address operation &x generates a
pointer of type *T to x. The operand must be addressable, that is,
either a variable, pointer indirection, or slice indexing operation;
or a field selector of an addressable struct operand; or an array
indexing operation of an addressable array. As an exception to the
addressability requirement, x may also be a (possibly parenthesized)
composite literal.
Your return value is none of those things, so you can't use the pointer method any more than you can write foo := &myFunc(). To work around this, you could save the return value on a variable to make it addressable. But most likely your function should return a pointer in the first place.
Also note that there are no references in Go. Everything is passed by value, and pointers are values just like any other.

https://golang.org/pkg/math/big/ the Text() method has a pointer receiver, which means that you can only call a.Text() if a is *big.Int.
*big.Int is a pointer to big.Int, see https://play.golang.org/p/dD70b0tPeGp for a fixed version of your code

Related

Add element to immutable vector rust

I am trying to create a user input validation function in rust utilising functional programming and recursion. How can I return an immutable vector with one element concatenated onto the end?
fn get_user_input(output_vec: Vec<String>) -> Vec<String> {
// Some code that has two variables: repeat(bool) and new_element(String)
if !repeat {
return output_vec.add_to_end(new_element); // What function could "add_to_end" be?
}
get_user_input(output_vec.add_to_end(new_element)) // What function could "add_to_end" be?
}
There are functions for everything else:
push adds a mutable vector to a mutable vector
append adds an element to the end of a mutable vector
concat adds an immutable vector to an immutable vector
??? adds an element to the end of a immutable vector
The only solution I have been able to get working is using:
[write_data, vec![new_element]].concat()
but this seems inefficient as I'm making a new vector for just one element (so the size is known at compile time).
You are confusing Rust with a language where you only ever have references to objects. In Rust, code can have exclusive ownership of objects, and so you don't need to be as careful about mutating an object that could be shared, because you know whether or not the object is shared.
For example, this is valid JavaScript code:
const a = [];
a.push(1);
This works because a does not contain an array, it contains a reference to an array.1 The const prevents a from being repointed to a different object, but it does not make the array itself immutable.
So, in these kinds of languages, pure functional programming tries to avoid mutating any state whatsoever, such as pushing an item onto an array that is taken as an argument:
function add_element(arr) {
arr.push(1); // Bad! We mutated the array we have a reference to!
}
Instead, we do things like this:
function add_element(arr) {
return [...arr, 1]; // Good! We leave the original data alone.
}
What you have in Rust, given your function signature, is a totally different scenario! In your case, output_vec is owned by the function itself, and no other entity in the program has access to it. There is therefore no reason to avoid mutating it, if that is your goal:
fn get_user_input(mut output_vec: Vec<String>) -> Vec<String> {
// Add mut ^^^
You have to keep in mind that any non-reference is an owned value. &Vec<String> would be an immutable reference to a vector something else owns, but Vec<String> is a vector this code owns and nobody else has access to.
Don't believe me? Here's a simple example of broken code that demonstrates this:
fn take_my_vec(y: Vec<String>) { }
fn main() {
let mut x = Vec::<String>::new();
x.push("foo".to_string());
take_my_vec(x);
println!("{}", x.len()); // E0382
}
The expression x.len() causes a compile-time error, because the vector x was moved into the function argument and we don't own it anymore.
So why shouldn't the function mutate the vector it owns now? The caller can't use it anymore.
In summary, functional programming looks a bit different in Rust. In other languages that have no way to communicate "I'm giving you this object" you must avoid mutating values you are given because the caller may not expect you to change them. In Rust, who owns a value is clear, and the argument reflects that:
Is the argument a value (Vec<String>)? The function owns the value now, the caller gave it away and can't use it anymore. Mutate it if you need to.
Is the argument an immutable reference (&Vec<String>)? The function doesn't own it, and it can't mutate it anyway because Rust won't allow it. You could clone it and mutate the clone.
Is the argument a mutable reference (&mut Vec<String>)? The caller must explicitly give the function a mutable reference and is therefore giving the function permission to mutate it -- but the function still doesn't own the value. The function can mutate it, clone it, or both -- it depends what the function is supposed to do.
If you take an argument by value, there is very little reason not to make it mut if you need to change it for whatever reason. Note that this detail (mutability of function arguments) isn't even part of the function's public signature simply because it's not the caller's business. They gave the object away.
Note that with types that have type arguments (like Vec) other expressions of ownership are possible. Here are a few examples (this is not an exhaustive list):
Vec<&String>: You now own a vector, but you don't own the String objects that it contains references to.
&Vec<&String>: You are given read-only access to a vector of string references. You could clone this vector, but you still couldn't change the strings, just rearrange them, for example.
&Vec<&mut String>: You are given read-only access to a vector of mutable string references. You can't rearrange the strings, but you can change the strings themselves.
&mut Vec<&String>: Like the above but opposite: you are allowed to rearrange the string references but you can't change the strings.
1 A good way to think of it is that non-primitive values in JavaScript are always a value of Rc<RefCell<T>>, so you're passing around a handle to the object with interior mutability. const only makes the Rc<> immutable.

How does Haskell runtime represent lazy values?

I don't even know how to express this question.
A assume there's a pointer to a non evaluated expression. If it's requested (by some strict function that coerces it) then the pointer value is replaced by the value evaluated. Right? Am I wrong?
So I assume every pointer has a flag stating if it has been evaluated or not.
And what if the evaluation is undefined, like the head of an empty list? What is stored in the "pointer"?
I assume there's a pointer to a non evaluated expression. If it's requested (by some strict function that coerces it) then the pointer value is replaced by the value evaluated. Right? Am I wrong?
That's the gist of it.
So I assume every pointer has a flag stating if it has been evaluated or not.
Every pointer points to some structure where you can find that kind of information.
And what if the evaluation is undefined, like the head of an empty list? What is stored in the "pointer"?
The pointer points to an expression whose evaluation throws an exception.
The details are in the following page of the GHC wiki; see in particular "Types of objects": https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary/rts/storage/heap-objects
Data constructors, function closures, thunks ("unevaluated expressions") are the main ones.

How to cast an interface{} to a struct pointer?

Interfaces already contain a pointer to a value, and I in my case it's a struct, and I need to get a struct pointer out of an interface{}.
The use case is with sync.Map, where I put a struct containing a lock into the map, and with the Load() method I can read an interface{} value. I want to get the pointer to the original struct, so I don't copy the lock.
The alternative is to add a pointer to the struct to the Map instead, then read it back and cast the interface{} to the struct pointer, but I'm curious if the first case can be achieved.
You can't do that. If you "wrap" a non-pointer value in an interface, you can only get a non-pointer value out of it, using either a type assertion or a type switch. And since type assertion expressions are not addressable, you can't get the address of the "value" wrapped in the interface.
If you only have a value wrapped in an interface, you won't be able to get a pointer to the original value that was wrapped in the interface. Why? Because the value wrapped in the interface may only be a copy, completely detached from the original. See examples and explanation here: How can a slice contain itself?
Note that under the hood the value actually wrapped may or may not be a pointer (depending on the value's size) even if you wrapped a non-pointer value, but this is implementation detail and is hidden from you. When you extract the value, you will of course get a non-pointer.

Convert interface{} to *[]int in golang

I receive an interface which is basically a slice. Now I want to convert it to a pointer to the slice. The problem is, that I have either the slice itself or a Pointer to an interface.
I can easily show in a code example:
func main(){
model := []int{1,2,3,4,5,6,7,8,10,11,133123123123}
method(model)
}
func method(model interface{}){
fmt.Println(reflect.TypeOf(model)) // this is of type []int
fmt.Println(reflect.TypeOf(&model)) // this is of type *interface{}
}
What I need is this type:
fmt.Println(reflect.TypeOf(result)) // this should be type *[]int
I know the type only on runtime, therefore I cannot just take
&(model.([]int))
Is there a way using golang reflection to receive this? the type 'int' is here actually not important, important is, that it is a Pointer to a slice. *[]interface{} would be okay either.
Edit:
To make the question more clear, I should have added: I am not interested in the data of the slice, but only in getting a pointer to a slice of same type (which can basically be empty). Therefore James Henstridge answers works perfectly.
Before trying to answer the question, it is worth stepping back and asking what the *[]int value you're after should point at?
Given the way method is called we can't possibly get a pointer to the model variable from the calling context, since it will only receive a copy of the slice as its argument (note that this is a copy of the slice header: the backing array is shared).
We also can't get a pointer to the copy passed as an argument since it is stored as an interface{} variable: the interface variable owns the memory used to store its dynamic value, and is free to reuse it when the a new value is assigned to it. If you could take a pointer to the dynamic value, this would break type safety if a different type is assigned.
We can obtain a *[]int pointer if we make a third copy of the slice, but it isn't clear whether that's what you'd necessarily want either:
v := reflect.New(reflect.TypeOf(model))
v.Elem().Set(reflect.ValueOf(model))
result := v.Interface()
This is essentially a type agnostic way of writing the following:
v := new([]int)
*v = model
var result interface{} = v
Now if you really wanted a pointer to the slice variable in the calling context, you will need to ensure that method is called with a pointer to the slice instead and act accordingly.

Take address of value inside an interface

How do I take the address of a value inside an interface?
I have an struct stored in an interface, in a list.List element:
import "container/list"
type retry struct{}
p := &el.Value.(retry)
But I get this:
cannot take the address of el.Value.(retry)
What's going on? Since the struct is stored in the interface, why can't I get a pointer to it?
To understand why this isn't possible, it is helpful to think about what an interface variable actually is. An interface value takes up two words, with the first describing the type of the contained value, and the second either (a) holding the contained value (if it fits within the word) or (b) a pointer to storage for the value (if the value does not fit within a word).
The important things to note are that (1) the contained value belongs to the interface variable, and (2) the storage for that value may be reused when a new value is assigned to the variable. Knowing that, consider the following code:
var v interface{}
v = int(42)
p := GetPointerToInterfaceValue(&v) // a pointer to an integer holding 42
v = &SomeStruct{...}
Now the storage for the integer has been reused to hold a pointer, and *p is now an integer representation of that pointer. You can see how this has the capacity to break the type system, so Go doesn't provide a way to do this (outside of using the unsafe package).
If you need a pointer to the structs you're storing in a list, then one option would be to store pointers to the structs in the list rather than struct values directly. Alternatively, you could pass *list.Element values as references to the contained structures.
A type assertion is an expression that results in two values. Taking the address in this case would be ambiguous.
p, ok := el.Value.(retry)
if ok {
// type assertion successful
// now we can take the address
q := &p
}
From the comments:
Note that this is a pointer to a copy of the value rather than a pointer to the value itself.
— James Henstridge
The solution to the problem is therefore simple; store a pointer in the interface, not a value.
Get pointer to interface value?
Is there a way, given a variable of interface type, of getting a
pointer to the value stored in the variable?
It is not possible.
Rob Pike
Interface values are not necessarily addressable. For example,
package main
import "fmt"
func main() {
var i interface{}
i = 42
// cannot take the address of i.(int)
j := &i.(int)
fmt.Println(i, j)
}
Address operators
For an operand x of type T, the address operation &x generates a
pointer of type *T to x. The operand must be addressable, that is,
either a variable, pointer indirection, or slice indexing operation;
or a field selector of an addressable struct operand; or an array
indexing operation of an addressable array. As an exception to the
addressability requirement, x may also be a composite literal.
References:
Interface types
Type assertions
Go Data Structures: Interfaces
Go Interfaces
In the first approximation: You cannot do that. Even if you could, p itself would the have to have type interface{} and would not be too helpful - you cannot directly dereference it then.
The obligatory question is: What problem are you trying to solve?
And last but not least: Interfaces define behavior not structure. Using the interface's underlying implementing type directly in general breaks the interface contract, although there might be non general legitimate cases for it. But those are already served, for a finite set of statically known types, by the type switch statement.

Resources