how declare two variables in for init in GoLang? [duplicate] - go

This question already has answers here:
Can you declare multiple variables at once in Go?
(8 answers)
Closed 5 years ago.
when i write:
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
var ret float64
for z := 1.0, n := 0;n < 10;n++ {
ret = z - (z*z - x) / 2*z
}
return ret
}
func main() {
fmt.Println(Sqrt(2))
}
syntax error: z := 1.0, n used as value.
and bring
z := 1.0
out of the for block below
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
var ret float64
z := 1.0
for n := 0;n < 10;n++ {
ret = z - (z*z - x) / 2*z
}
return ret
}
func main() {
fmt.Println(Sqrt(2))
}
it's ok so how can i define two variables in init of the for block?

A For clause has an Init Statement which is a Simple Statement, including only one Assigment
So in your case, you cannot declare multiple variable with different type/values. You could use a tuple assignment though
for z, n := 1.0, 0; n < 10; n++ {
(playground)

Related

golang operator % not defined on float64

There's a leetcode test 326. Power of Three with a Mathematics method with java:
public class Solution {
public boolean isPowerOfThree(int n) {
return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
}
}
When I intend to convert this solution to Golang Like
import "math"
func isPowerOfThree(n int) bool {
return (math.Log10(float64(n)) / math.Log10(3)) % 1 == 0.0
}
then here comes the compile error like
Line 4: Char 53: invalid operation: math.Log10(float64(n)) / math.Log10(3) % 1 (operator % not defined on float64) (solution.go)
I check the math package but there's no supported function like % operator, Is there any valid operator like % in Golang? thanks a lot :)
TLDR: _, frac := math.Modf(f)
You could use func Mod(x, y float64) float64 in math package.
package main
import (
"math"
)
func isPowerOfThree(n int) bool {
return math.Mod((math.Log10(float64(n)) / math.Log10(3)), 1.0) == 0.0
}
You could also use func Modf(f float64) (int float64, frac float64).
package main
import (
"math"
)
func isPowerOfThree(n int) bool {
_, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return frac == 0.0
}
We can not use just below function, as there can be more than one digit after decimal in frac
_, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return frac == 0.0
So to resolve this, use below logic
func isPowerOfThree(n int) bool {
quo,_ := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return n == int(math.Pow(3, quo))
}

Odd behavior of scopes [duplicate]

This question already has answers here:
My object is not updated even if I use the pointer to a type to update it
(3 answers)
Closed 3 years ago.
Consider the following minimal example:
package main
import "fmt"
type runner interface {
s1(int)
s2(int)
}
type test struct {
x1 []int
x2 []int
}
func (t test) s1(v int) {
t.x1 = append(t.x1, v)
t.s2(v)
}
func (t test) s2(v int) {
t.x2[v] = v
}
func main() {
t := test{
x1: make([]int, 0),
x2: make([]int, 10)}
for i := 0; i < 10; i++ {
t.s1(i)
}
fmt.Println(t)
}
Now if you run it, you will get a result like this:
{[] [0 1 2 3 4 5 6 7 8 9]}
meaning that the x1 array is never populated. Or actually, it is, but resets on each time s1 function exits. s2 works just fine placing items in a pre-defined array.
Does anyone know what exactly is going on here? Is it because of the scope of array amends? It seems a little counter intuitive.
P.S. I do understand that x1 is a slice, where x2 is an actual pre-defined array. My own theory goes that if you work with "slices", they can only be changed within a specific scope, not anywhere else.
Value receiver makes a copy of the type and pass it to the function.
Just make it pointer and you are good to go:
func (t *test) s1(v int) {
t.x1 = append(t.x1, v)
t.s2(v)
}
Output:
&{[0 1 2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7 8 9]}
Code:
package main
import "fmt"
type runner interface {
s1(int)
s2(int)
}
type test struct {
x1 []int
x2 []int
}
func (t *test) s1(v int) {
t.x1 = append(t.x1, v)
t.s2(v)
}
func (t test) s2(v int) {
t.x2[v] = v
}
func main() {
t := &test{
x1: make([]int, 0),
x2: make([]int, 10)}
for i := 0; i < 10; i++ {
t.s1(i)
}
fmt.Println(t)
}

Go tour #18. How do I pass in integers to Pic?

The following code errors with index out of range. I tried modifying main to
pic.Show(Pic(500, 500)) but that changes the argument from function to the return type and it fails to compile. How do I pass in integers if the pic.Show is expecting a function as an argument.
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
mypic := [][]uint8{}
for y := 0; y < dy; y++ {
mypic[y] = []uint8{}
for x := 0; x < dx; x++ {
mypic[y][x] = uint8((x + y) / 2)
}
}
return mypic
}
func main() {
pic.Show(Pic)
}
You don't. The Go Tour program will pass Pic test values to your program. Your problem is in your code: panic: runtime error: index out of range. [][]uint8{} and []uint8{} allocate zero y and zero x slice elements. Use make to allocate your y and x slices. For example,
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
pixels := make([][]uint8, dy)
for y := 0; y < dy; y++ {
pixels[y] = make([]uint8, dx)
for x := 0; x < dx; x++ {
pixels[y][x] = uint8((x + y) / 2)
}
}
return pixels
}
func main() {
pic.Show(Pic)
}
Reference: Making slices, maps and channels, The Go Programming Language Specification

undefined <type float32 has no field or method sum> error.How do I fix it?

this is my program.When I run it, it gives the following error - a.sum undefined (type float32 has no field or method sum)
package main
import (
"fmt"
)
type Calculation interface {
operation(input []float32)
}
type Addition struct {
sum float32
}
func (a Addition) operation(input []float32) {
a.sum = input[0]
for _, a := range input[1:] {
a.sum += a
}
fmt.Println("Sum :", a.sum)
}
func main() {
var n int
fmt.Println("Enter the no of inputs : ")
fmt.Scanln(&n)
var input []float32
input = make([]float32 , n)
fmt.Println("Enter the numbers ")
for i:=0 ; i <n ; i++ {
fmt.Scanln(&input[i])
}
var c Calculation
i := Addition{0}
c = i
c.operation(input)
}
I have written 3 more functions Subtraction , Multiplication and Division with Addition. All of them follow similar format but those three run with out any error, Only addition is giving this error. Unable to figure out why.
Your variable a in the loop shadows the variable a representing Addition. Changing your loop to this will solve the problem:
for _, v := range input[1:] {
a.sum += v
}

Static local variable in Go

Is it possible to define a local variable in Go that can maintain its value from one function call to another? In C, we can do this using the reserved word static.
Example in C:
int func() {
static int x = 0;
x++;
return x;
}
Use a closure:
Function literals are closures: they may refer to variables defined in
a surrounding function. Those variables are then shared between the
surrounding function and the function literal, and they survive as
long as they are accessible.
It doesn't have to be in global scope, just outside the function definition.
func main() {
x := 1
y := func() {
fmt.Println("x:", x)
x++
}
for i := 0; i < 10; i++ {
y()
}
}
(Sample on the Go Playground)
You can do something like this
package main
import (
"fmt"
)
func main() {
f := do()
f() // 1
f() // 2
}
func do() (f func()){
var i int
f = func(){
i++
fmt.Println(i)
}
return
}
Link on Playground https://play.golang.org/p/D9mv9_qKmN
Declare a var at global scope:
var i = 1
func a() {
println(i)
i++
}
Like Taric' suggestion, but with staticCounter() returning an int function
package main
import (
"fmt"
)
func staticCounter() (f func()(int)){
var i int
f = func()(int){
i++
// fmt.Println(i)
return i
}
return
}
func main() {
f := staticCounter()
g := staticCounter()
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println(g())
fmt.Println(g())
}
Use Function closure
In following example, variable sum behaves like a separate static for each closure a1 and a2.
package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
a1,a2 := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
a1(i),
a2(-1*i),
)
}
}
Output
0 0
1 -1
3 -3
6 -6
10 -10
15 -15
21 -21
28 -28
36 -36
45 -45
In all the other answers, the function containing a static variable is assigned in the main.
Here is how you can define and assign that function in the global scope.
var myFunction = func() func(type1, type2) type3 {
myStaticVariable := []string {"hello", "world"}
return func(arg1 type1, arg2 type2) type3 {
// use arg1, arg2 and myStaticVariable here
}
}()
// A var x1 is local to main(), is not a global var.
// A static var is one that can't be accesed from others functions just
// like global vars.
// A static var dont disappears when the function ends.
// So is what x1 n x2 are pretending in this program.
package main
import (
"fmt"
)
/*
int func() { // x static inside a function.
static int x = 0;
x++;
return x;
}
*/
//
func main() {
//
var x1 int = 0
var x2 int = 100
//
for i := 0; i < 10; i++ { // call to a "static" var x
x1 = fun1(&x1)
x2 = fun2(&x2)
fmt.Printf("%d %d \n", x1, x2)
} //
test1(x1, x2) // a funct needs parameters to see x1 n x2
} //main
//
func fun1(p *int) int {
//
*p++ // save value
return *p //counter x1
}
//
func fun2(p *int) int {
*p++ // save value
return *p //counter x2
}
//
func test1(x1 int, x2 int) {
fmt.Println("\"x1\" y \"x2\" ", x1, x2)
}

Resources