Trying to understand structs in Golang? [closed] - go

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 days ago.
Improve this question
I don't seem to understand why I cannot re-assignee inner struct?
I have two structs, outer and inner. I am able to manipulate with primitive values, but not with nested struct values.
type Vertex struct {
X int
Y int
K VertexInner
}
type VertexInner struct {
X int
Y int
}
func main2() {
inner := VertexInner{3,4}
v := Vertex{1, 2, inner}
p := &v
p.X = 1e9
var newInner *VertexInner
newInner = new(VertexInner)
newInner2 := VertexInner{
X: 1,
Y: 22,
}
p.K = newInner; // NOT WORKING
p.K := newInner2 ; // NOT WORKING
}

Related

why the length of this go slice is 4 and why the output has the space in slice? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am new to golang and while running this code snippet I am getting the len as 4, trying to understand why so ?
package main
import "fmt"
type phone struct {
model string
camera Camera
ram int
}
type Camera struct {
lens string
aparature int
}
func main() {
var m = make(map[string]phone)
myphn1 := phone{model: "iphone", camera: Camera{"20", 4}, ram: 6}
myphn2 := phone{model: "pixel", camera: Camera{"50", 2}, ram: 6}
m["myphn1"] = myphn1
m["myphn2"] = myphn2
var k = make([]string, len(m))
for key, _ := range m {
k = append(k, key)
}
fmt.Println(k)
fmt.Println(len(k))
}
I understand this adds size of 2 while creating, but while printing it gives somelike this , is the space in answer for 2 unallocated entries ?
[ myphn2 myphn1]
4
This creates a slice of length 2 (len(m) is 2 here):
var k = make([]string, len(m))
This adds two elements to it, for a total of 4:
for key, _ := range m {
k = append(k, key)
}
If you want to preallocate a slice, you need to provide a length of zero along with the desired capacity:
var k = make([]string, 0, len(m))
This is covered with examples in the Tour of Go.
You create a slice with length 2, and appended two more elements to it, so the length is 4.
what you probably want to do is to create a slice with capacity 2:
var k = make([]string,0,len(m))

why float 32 and float64 printed as integer in go? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I was looking at "A Tour of Go" and saw that
package main
import (
"fmt"
"math"
)
func main() {
var x, y int = 3, 4
var f float64 = math.Sqrt(float64(x*x + y*y))
var z uint = uint(f)
fmt.Println(x, y, z, f)
}
when I run this code it prints 3 4 5 5 shouldn't it be 3 4 5 5.0 I am totally new to go looked up documentation but i couldn't find any answer for this
math.Sqrt -> float64
however you are using fmt.Println.
Try
fmt.Printf("%.1f", f)
"Println formats using the default formats for its operands and writes to standard output." https://golang.org/pkg/fmt/#Println

How to get nearest int in operation on integers in golang? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'd like to get nearest value of an operation envolving division of two integers. My initial function is like this, which always rounds to the lower integer.
func Percent(x int, y int) int {
p := x * 100 / y
return p
}
So for example when the result is 5.75, I'd like to be rounded to 6, but the above function returns 5.
I tried to use math.Round but it needs receive a float type and returns a float type. So that needs lots of conversion which gets dirty whn there are many parameters in the operation.
So I'm wondering what is the clean idomatic way to round to nearest integer?
Your operations are using all integer so the output will be an integer, so definitely you need to cast them to float first, then you can convert float to nearest int (5.75 to 5)
For that below code will work for you. You even don't need to use math.Round
func Percent(x int, y int) int {
p := float64(x * 100) / float64(y)
return int(p+0.5)
}
Just create float values from your ints, then an int value from a rounded float result:
func RoundPercent(x int, y int) int {
p := float64(x * 100) / float64(y)
return int(math.Round(p))
}

Why do we add & in the following script, if it does not make any change on the result? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
package main
import (
"fmt"
"math"
"reflect"
)
type Vertex struct {
X, Y float64
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := &Vertex{3, 4} // Whether or not with "&", the values don't change below.
fmt.Printf("Before scaling: %+v, Abs: %v\n", v, v.Abs())
v.Scale(5)
fmt.Printf("After scaling: %+v, Abs: %v\n", v, v.Abs())
fmt.Println(reflect.TypeOf(Vertex{3,4}))
}
Hello, I am learning golang now. I do not understand what is the use of adding "&", if it does not make any change on the result value?
I thought we add "&" to variables to get the memory address. If we can add "&" to Vertex{3,4}, does this mean it is variable? Confused.
I assume you're talking about Vertex vs &Vertex? Yes, adding & means that v now contains an address to a struct of type Vertex, whereas without the &, v would hold the struct directly.
In your example, using the address, or the struct directly, makes no difference. In many other cases, the distinction is very important.

How do I element-wise square root a gonum matrix? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I was going to use Pow but it only seems to accept powering by integer values.
For example, the element-wise square root matrix m of matrix a.:
a = ⎡ 4 9⎤
⎣16 25⎦
m = ⎡2 3⎤
⎣4 5⎦
For an element-wise square root of a matrix, write something like this:
package main
import (
"fmt"
"math"
"gonum.org/v1/gonum/mat"
)
func main() {
a := mat.NewDense(2, 2, []float64{
4, 9,
16, 25,
})
fa := mat.Formatted(a, mat.Prefix(" "), mat.Squeeze())
fmt.Printf("a = %v\n\n", fa)
m := new(mat.Dense)
m.Apply(func(i, j int, v float64) float64 { return math.Sqrt(v) }, a)
fm := mat.Formatted(m, mat.Prefix(" "), mat.Squeeze())
fmt.Printf("m = %v\n\n", fm)
}
Output:
a = ⎡ 4 9⎤
⎣16 25⎦
m = ⎡2 3⎤
⎣4 5⎦

Resources