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 3 months ago.
Improve this question
I am trying to compare 2 structs of the array type in Golang in order to know if having struct1 obtained from web scrapping is equal to struct 2, which is data fetched from the database.
It is the way that I have thought to be able to know if there has been a change between the external web and my database.
The structs is:
type Exchange struct {
Name string `gorm:"Column:name" json:"name"`
Buy float64 `gorm:"Column:buy" json:"buy"`
Sell float64 `gorm:"Column:sell" json:"sell"`
}
The result after consult is from scrapping:
&[{Dólar 38.5 41 } {Euro 38.82 43.57 } {P. Argentino 0.05 0.35 } {Real 6.95 8.95 }]
From web
&[{Dólar 38.5 41} {Euro 38.82 43.57} {P. Argentino 0.05 0.35} {Real 6.95 8.95}]
My Code:
fmt.Println(exchanges)
dbExchanges := getExchangesFromDB()
fmt.Println(dbExchanges)
if exchanges == dbExchanges {
fmt.Println("is equal")
} else {
fmt.Println("no is equal")
}
fmt.Println("Struct equal: ", reflect.DeepEqual(exchanges, dbExchanges))
Result:
no is equal
Struct equal: false
In the first if you are comparing the memory address of the two variables instead of theirs values. In the second if clause (using reflect.DeepEqual) you are comparing their values.
Related
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 2 years ago.
Improve this question
How did fmt.Printf() treat %x? when the parameter is a var or const. I read from books that const has no Type before been specified, it is hard to understand.
const AValue int32 = 1049088
func main() {
fmt.Printf("%#x\n", 1049088)
fmt.Printf("%#x\n", AValue)
fmt.Printf("%#x\n", int(time.Friday))
fmt.Printf("%#x\n", time.Friday)
}
logs :
0x100200 // 1049088
0x100200 // AValue
0x5 // int(time.Friday)
0x467269646179 // time.Friday is a type Weekday int
Is `0x467269646179` some kind address of time.Friday?
From the docs:
Except when printed using the verbs %T and %p, special formatting
considerations apply for operands that implement certain interfaces.
In order of application:
...
5. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be
formatted as required by the verb (if any).
For string the verb formatting is defined as:
%s the uninterpreted bytes of the string or slice
%q a double-quoted string safely escaped with Go syntax
%x base 16, lower-case, two characters per byte
%X base 16, upper-case, two characters per byte
So 0x467269646179 is the base 16, lower-case, two characters per byte of the output of time.Friday.String().
https://play.golang.org/p/avV-X2uiL1D
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 2 years ago.
Improve this question
In JavaScript I can do something like this:
const periods = {
'mercury': 0.2408467,
'venus': 0.61519726,
'earth': 1.0,
'mars': 1.8808158,
'jupiter': 11.862615,
'saturn': 29.447498,
'uranus': 84.016846,
'neptune': 164.79132,
};
const planetName = prompt();
const period = periods[planetName];
How can I do similar thing in go-lang?
You came very close to answering your own question. :)
Just put those tags on google.
package main
import (
"fmt"
)
func main() {
periods := map[string]float32{
"mercury": 0.2408467,
"venus": 0.61519726,
}
fmt.Println(periods["mercury"])
}
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 3 years ago.
Improve this question
I want to find the difference between two numbers in Go and the result should not be in "-".
Please find my code below:
dollarValue := 240000 - 480000
The result is "-240000". But my expected output is just "240000". Can anybody help on how to calculate the difference between these two numbers.
Your title is misleading. It should be states without negative instead of - operator.
Basically what you want to get is the absolute different between two numbers
You have two options:
Use if/else condition to return the positive result if the result is negative
Use math.Abs (need to convert from/to float)
Just implement your own method
func diff(a, b int) int {
if a < b {
return b - a
}
return a - b
}
and use it like this:
dollarValue := diff(240000, 480000)
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 try to implement Sparse sets from this article in Go and make it into a package. In early implementation, the API is clean and minimal with only exported type Sparse and exported method Insert, Delete, Has, Union, Intersection, Clear, and Len, pretty much only basic sets operation.
Later on, I want to add new functionality, sets that can reserve an element automatically (lets call it AutoSparse). If Sparse have Insert(k int) which insert k into sets, AutoSparse have Reserved() reserved an available element. If I have {0 1 2 4 5} in AutoSparse, when i call Reserve() it must add 3, not 6 so now it become {0 1 2 4 5 3}. Here's the implementation at playground.
As you can see, in order to maintain which element to added into sets, it doesn't add new field in the struct and I want to keep it like that.
My Question is how to add that new functionality to my package without adding new exported type AutoSparse to keep the API clean and minimal?
This is what i already try:
I can use interface to hide implementation but function signature is different, one use Insert(k int), the other use Reserve(), even if I use name Insert() it still different, or should I use Insert(k int) but didn't use k at all? it can but it's awkward.
I can't use the same struct to implement this because once you Use Reserve() to add element, you can't use Insert(k int) because it will messed up the reserved element, even Delete and Clear is different.
You can use k... int as parameter.
func (sparse Sparse) Insert(k... int) error {
if len(k) == 0 {
// first case
return nil
} else if len(k) == 1 {
// second case
return nil
} else {
return errors.New("Too many arguments")
}
}
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 7 years ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm trying to solve "The go programming lanaguage" exercise #1.4 which requires me to have a set. I can create a set type but why doesn't the language come with one ? go, having come from google, where guava also originated, why didn't the language designers opt for adding support for fundamental data structures ? why force your users to create their own implementations for something so basic as a set ?
One reason is that it is easy to create a set from map:
s := map[int]bool{5: true, 2: true}
_, ok := s[6] // check for existence
s[8] = true // add element
delete(s, 2) // remove element
Union
s_union := map[int]bool{}
for k, _ := range s1{
s_union[k] = true
}
for k, _ := range s2{
s_union[k] = true
}
Intersection
s_intersection := map[int]bool{}
if len(s1) > len(s2) {
s1, s2 = s2, s1 // better to iterate over a shorter set
}
for k,_ := range s1 {
if s2[k] {
s_intersection[k] = true
}
}
It is not really that hard to implement all other set operations.
Partly, because Go doesn't have generics (so you would need one set-type for every type, or fall back on reflection, which is rather inefficient).
Partly, because if all you need is "add/remove individual elements to a set" and "relatively space-efficient", you can get a fair bit of that simply by using a map[yourtype]bool (and set the value to true for any element in the set) or, for more space efficiency, you can use an empty struct as the value and use _, present = the_setoid[key] to check for presence.
Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...
The other reason is, that it's not clear at all what the "right" implementation of a set is:
There is a functional approach:
func IsInEvenNumbers(n int) bool {
if n % 2 == 0 {
return true
}
return false
}
This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.
Or you do a has-like approach like Dali showed.
A map does not have that problem, since you store something associated with the value.
Another possibility is to use bit sets, for which there is at least one package or you can use the built-in big package. In this case, basically you need to define a way to convert your object to an index.