What's wrong with this simple script? - go

I study functions, wrote a simple script for the textbook, and there were 2 errors.
package main
import "fmt"
func zero(x int) {
x = 0
return x
}
func main() {
x := 5
x = zero(x)
fmt.Println(x)
}
too many arguments to return (string return x)
How is "too many"? It's only one!
zero(x) used as value (string x = zero(x))
I don't understand what he says to me.

int in func
package main
import "fmt"
func zero(x int) int {
x = 0
return x
}
func main() {
x := 5
x = zero(x)
fmt.Println(x)
}

package main
import "fmt"
func zero(x int) int {
x = 0
return x
}
func main() {
x := 5
x = zero(x)
fmt.Println(x)
}

I believe this is closer to the original idea...
package main
import "fmt"
func zero(x *int) {
*x = 0
return
}
func main() {
x := 5
zero(&x)
fmt.Println(x)
}

too many means that your function is returning more values that the function signature specifies.
In your case, your function signature func zero(x *int), says that this function doesn't returns ANY params, and inside the function body, you're returning ONE value: return x. So 1 is too many for 0 expected. Exactly 1 more.
Then zero(x) used as value is telling you that you're calling a function that doesn't return ANY value, and you're trying to assign the non-existent return value to a variable: x = zero(x).
That's why the compiler tells you about using zero(x) as a value

Related

golang return function and assigned value

I am going to learn 'golang return function' but I'm seriously confused.
why this code return "7" ?
how the value is assigned to "y" ?
package main
import "fmt"
func maked(x float64) func(float64) float64 {
fn := func(y float64) float64 {
return x - y
}
return fn
}
func main() {
test := maked(12)
fmt.Println(test(5))
// printed 7
}
test := maked(12) returns a function like below.
fn := func(y float64) float64 {
return 12 - y
}
and now test have that function. So test(5) runs above function with y = 5.
so 12 - 5 = 7

How to fill a slice with scan values

I'm brand new to Go and having trouble getting fmt.scan() to fill a slice. The number of input values is dynamic and I can't use a for loop. My initial thought was to try this:
package main
import "fmt"
func main() {
var x []int
fmt.Println("Enter input")
fmt.Scanf("%v", append(x))
fmt.Println(x)
}
Which obviously doesn't work. Can someone point me in the right direction?
[Get] fmt.Scan() to fill a slice. The number of input values is dynamic and I can't use a for loop.
Perhaps, something like this:
package main
import "fmt"
func input(x []int, err error) []int {
if err != nil {
return x
}
var d int
n, err := fmt.Scanf("%d", &d)
if n == 1 {
x = append(x, d)
}
return input(x, err)
}
func main() {
fmt.Println("Enter input:")
x := input([]int{}, nil)
fmt.Println("Input:", x)
}
Output:
Enter input:
1
2 3
4
5 6 7
Input: [1 2 3 4 5 6 7]
ADDENDUM:
When storage is allocated for a variable or a new value is created, and no explicit initialization is provided, the variable or value is given a default value, the zero value for its type: nil for slices. Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T. []int(nil) is a conversion to the zero value for the slice value []int.
x := input([]int(nil), nil)
is equivalent to
x := input([]int{}, nil)
or
var x []int
x = input(x, nil)
I have revised my answer to use:
x := input([]int{}, nil)
I'm new to Go, so this are my 2cents as a newbie.
func main(){
var numsToInput int
fmt.Println("Welcome user!")
fmt.Println("How many numbers would you like to scale today?")
fmt.Scan(&numsToInput)
fmt.Println("Type please the ", num, " numbers: ")
var values []float32 // Empty slice
for i := 0; i < num; i++{
var val float32
fmt.Scanln(&val)
values = append(values, val)
}
fmt.Println(values)
}
It's not a very elaborate program, but certainly it's simple.
I hope it was useful.
Using simple packages and more logic, you could try this,
package main
import "fmt"
func main() {
var ele rune
var size int
var sli = make([]int,0,1)
size = cap(sli)
for i:=0; i<=size; i++{
if i>=len(sli){
size=size+1
}
ele = 0
fmt.Println("Enter a number to add: ")
fmt.Scan(&ele)
if ele==0 {
fmt.Println("Stopping!")
break
}
sli = append(sli, int(ele))
}
fmt.Println(sli)
}
The code would stop and print the slice when you enter anything other than an integer.

get sum of bigInt number golang

Hi i am new to the golang programming language. I can get the bigint
value from the factoral function but it is not working with the add
function.
i have had the add function accepting bigint but when i try to add a
.Mod and .Div methods it returns 0 fro some reason. the if else
statement in the add function is an old statement i was using when i
had int values coming from the factoral function.
it worked perfectly when it was as int value. When i attempted to
alter the if else statement to accept bigint values i couldn't get it
to work at all.
I have tried the .Mod and .Div methods and they are printing out the
correct values. But when i try to .Add them together it always returns
0. even if the values are "22", "2". I've put the if else statement back to the original int values for now.
if anyone can help me out with this one i would be very greatful.
package main
import (
"fmt"
"math/big"
)
func factoral(n uint64) (r *big.Int) {
one, bn := big.NewInt(1), new(big.Int).SetUint64(n)
r = big.NewInt(1)
if bn.Cmp(one) <= 0 {
return
}
for i := big.NewInt(2); i.Cmp(bn) <= 0; i.Add(i, one) {
r.Mul(r, i)
}
return
}
func add(number *big.Int) *big.Int {
//this the statement that works with normal int values
if number/10 < 10 {
return sum + number/10
} else {
return sum + add(number/10)
}
}
func main() {
fmt.Println(add(factoral(100)))
}
Fixed it
package main
import (
"fmt"
"math/big"
)
func factoral(n uint64) (r *big.Int) {
one, bn := big.NewInt(1), new(big.Int).SetUint64(n)
r = big.NewInt(1)
if bn.Cmp(one) <= 0 {
return
}
for i := big.NewInt(2); i.Cmp(bn) <= 0; i.Add(i, one) {
r.Mul(r, i)
}
return
}
func add(number *big.Int) *big.Int {
ten := big.NewInt(10)
sum := big.NewInt(0)
mod := big.NewInt(0)
for ten.Cmp(number)<0 {
sum.Add(sum, mod.Mod(number,ten))
number.Div(number,ten)
}
sum.Add(sum,number)
return sum
}
func main() {
fmt.Println(add(factoral(100)))
}
Seems your issue was likely with the way the Big Int object whose method you invoke is going to be the one the value is assigned to, and not necessarily one of the arguments.
See: https://golang.org/pkg/math/big/#Int.Div

Calculating large exponentiation in Golang

I've been trying to calculating 2^100 in Golang. I understand the limit of numeric type and tried using math/big package. Here's what I've tried but I can't figure out why it doesn't work.
I've used computation by powers of two method to calculate the exponentiation.
package main
import (
"fmt"
"math/big"
)
func main() {
two := big.NewInt(2)
hundred := big.NewInt(50)
fmt.Printf("2 ** 100 is %d\n", ExpByPowOfTwo(two, hundred))
}
func ExpByPowOfTwo(base, power *big.Int) *big.Int {
result := big.NewInt(1)
zero := big.NewInt(0)
for power != zero {
if modBy2(power) != zero {
multiply(result, base)
}
power = divideBy2(power)
base = multiply(base, base)
}
return result
}
func modBy2(x *big.Int) *big.Int {
return big.NewInt(0).Mod(x, big.NewInt(2))
}
func divideBy2(x *big.Int) *big.Int {
return big.NewInt(0).Div(x, big.NewInt(2))
}
func multiply(x, y *big.Int) *big.Int {
return big.NewInt(0).Mul(x, y)
}
BigInt package allows you to calculate x^y in log time (for some reason it is called exp). All you need is to pass nil as a last parameter.
package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Println(new(big.Int).Exp(big.NewInt(5), big.NewInt(20), nil))
}
If you are interested how to calculate it by yourself, take a look at my implementation:
func powBig(a, n int) *big.Int{
tmp := big.NewInt(int64(a))
res := big.NewInt(1)
for n > 0 {
temp := new(big.Int)
if n % 2 == 1 {
temp.Mul(res, tmp)
res = temp
}
temp = new(big.Int)
temp.Mul(tmp, tmp)
tmp = temp
n /= 2
}
return res
}
or play with it on go playground.
For example,
package main
import (
"fmt"
"math/big"
)
func main() {
z := new(big.Int).Exp(big.NewInt(2), big.NewInt(100), nil)
fmt.Println(z)
}
Output:
1267650600228229401496703205376
Since it's a power of two, you could also do a bit shift:
package main
import (
"fmt"
"math/big"
)
func main() {
z := new(big.Int).Lsh(big.NewInt(1), 100)
fmt.Println(z)
}
Output:
1267650600228229401496703205376
You are returning immediately if power % 2 == 0. Instead, you just want to get the result of base ** (power /2). Then multiply result * result, and if power is even then multiply base to that.
To compute 2^100
package main
import (
"fmt"
"math/big"
)
func main() {
n := big.NewInt(0)
fmt.Println(n.SetBit(n, 100, 1))
}
Playground
package main
import(
"fmt"
"math/big"
)
func main() {
bigx, power10 := new(big.Int), new(big.Int)
var x int64
bigx.SetInt64(x) //set x int64 to bigx
power10.Exp(big.NewInt(10), bigx, nil) //power10 *big.Int points to solution
str10 := power10.Text(10)
fmt.Printf(str10) // print out the number and check for your self
}

Access one of the multiple result parameters return by a function in go

Here's the sample code (from tour.golang.org),
package main
import "fmt"
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
func main() {
x, _ := split(17)
fmt.Println(x)
}
I would like to know if it is possible to shorten the main function to just a single line. Logically there should be a way (might not look very elegant in this case though) to access only first result parameter returned from function and print it.
fmt.Println is a variadic function, so you can just pass the split function as a parameter:
func main() {
fmt.Println(split(17))
}
see it working in full here: http://play.golang.org/p/c1zkFVMe11

Resources