Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
Why does the print function in this code only execute once?
package main
import (
"fmt"
"unsafe"
)
func main() {
b := make([]byte, 10)
s := *(*string)(unsafe.Pointer(&b))
b[0] = 'A'
fmt.Println(s)
fmt.Println("www")
}
As noted in comments above, whether the above works (whatever "works" really means) or not, depends on vagaries of the underlying system. (My second comment was wrong and I have deleted it.) In normal code, avoid unsafe: you need to know a lot about what you are doing with it, to use unsafe safely. Worse, even if you do know what you are doing, and use it safely today, things you do with it now might break in a future Go release.
I asked why you were trying this in the first place:
I just want to try to convert the variable b into a string with zero-copy ...
In this case, since you are creating b, you can just create it as a string in the first place.
More generally, there is an outstanding feature request for this. See (closed) issue 25484 and still-open issue 19367. I think it unlikely that these will be adopted for Go version 1.
Note that if you do make a string header that grants access to the slice data, the underlying bytes in the string are not read-only, unlike normal Go strings.
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 7 months ago.
Improve this question
All of these work in golang:
var i int = 2
var i = 2
i := 2
Why are we saying golang is statically typed? It should be dynamically typed right?
If golang is performing type resolution during compile time, then it should be increasing the compile time of the program, so why is golang known for its faster compile time?
In all these instances, i is an integer. In the case of i := 2, the variable i is implicitly an integer. You could later assign 51 or 42 to i, but you could not assign any other datatype to is.
Go just implicitly infers the datatype from the initial assignment.
Pasting #mkopriva's answer.
It's statically typed because you can't change a variable's type at runtime. Not specifying a variable's type explicitly does not mean that variable does not have a type, in these situations "type inference" is used. e.g. the compiler looks looks at the RHS of the expression, sees 2, and decides, based on rules enumerated in the spec, what type to give to the variable.
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 last year.
Improve this question
Good day for all readers!
I have api service which needs key for some decrypt issues. Key calculates all time when I make request. That is wrong from an architectural point of view.
The option with environments (.env, viper...) drops because, in the future, I want to bring out this module to a separate library.
Hint me, how it is possible without using environments to calculate the key when starting the application and use it until stopping the application?
A global var starts with a capital, so it is reachable from within other packages.
But... it's actually bad behaviour, because those other packages can change it.
Having a non capital one, still means that functions in the same package can change it.
Perhaps you can use a constant?
or make a singleton variable, see :
https://goplay.tools/snippet/9k7FLYbbvoo
If you are sure you need a global variable, you can do this:
package main
var globalVar string = "My string"
func init(){
globalVar = "The new value of the variable"
}
func main(){
println(globalVar)
}
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 1 year ago.
Improve this question
As in java8:
someList.stream().map(e->e.getXXX()).toList()
For example, I have a Student array/slice, and the struct Student contains properties like Id, Name, and so on.
I want to extract all Ids into a NEW array/slice with one-line code like java8 as mentioned above, instead of range. Is there is an example?
Currently there is not an easy, builtin way to do this. Although Go has first-class functions and lexical closure, it's not possible to write a function like map that will operate on arbitrary types in the way you want. (Also, there's no compact lambda syntax, but I consider that a relatively minor issue).
Instead, you have to do one of the following:
Operate on interface{}. While this would let you write a func map([]interface{}, func(interface{})interface{}) []interface{}, you lose compile-time type safety, you lose performance, and a []interface{} is not a []string (or whatever the type is of the field you wanted to fetch), nor can you even type-assert it to one, so working with the result is cumbersome.
Use code-generation. There are libraries out there that will generate map/filter/etc. code for you, specialized to given types, so that none of the disadvantages of #1 apply. And Go ships with a Go parser in the standard library, so most code generators are fairly robust. But code generation is a separate build step, hampers debuggability, and can hurt the clarity of code.
Just live with boilerplate, writing lots of loops, and forget about trying to achieve functional style.
Wait for Go 1.18 to bring generics, which should make libraries of functional idioms a lot more practical.
Most experienced Go users would recommend approach #3, and so do I (reluctantly).
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 1 year ago.
Improve this question
I've recently watch this talk by Liz Rice (which I highly recommend!), and I've seen that instead of writing:
func main() {
if err := someFunc(); err != nil {
panic(err)
}
}
she does:
func main() {
must(someFunc())
}
func must(err error) {
panic(err)
}
Is it an idiomatic way to handle errors? IMO it does not improve readability, and I feel that it does not follows the Go proverb "Clear is better than clever". What do you think?
The MustXXX(error) pattern is useful when the error could arise at runtime, but whether it does is actually decided at compile time. Meaning if the source code is what it should be, the error will not happen at runtime.
Shining examples are template.Must() and regexp.MustCompile(). If you provide a valid template or valid regexp in the source code, parsing them will never fail at runtime. In these situations using Must() results in shorter and clear code. Tests should be supplied to detect if invalid template or regexp is used in the source, so the mistake is detected early (when tests are run).
Other than that (when an error could happen based on runtime conditions like user input, data read from external source etc.), the Must() pattern is obviously not advised and you should handle the error properly.
See related: Multiple values in single-value context
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I have hundreds of yaml files (related to K8s and Helm) with different structures which I use python to edit if needed. I am deciding to learn Go and I wanted to write a new script with go to edit these files but surprisingly I saw that people are creating the yaml structure before reading the yaml file(GO reading YAML file and mapping to slice of structs and Go parse yaml file). What I mean is they create a struct with all the keys in the yaml file with the correct indentation.
I want to know is there a library in Go that you just give it the path to the file and it reads the yaml file dynamically? I want something like python that it reads the file and then you can just access the data similar to a dictionary or data['k1']['k2'] and when you are done with editing just write it back to the file.
Update
I cannot understand what is wrong with asking about libraries? Isn't this what eventually happens? People suggest different solutions and most of them are using different libraries. On the other hand, I am trying to see where and how to use Go, why my question get off-topic?
You can tell the yaml package to unmarshal into an empty interface:
package main
import (
"gopkg.in/yaml.v3"
"reflect"
)
func main() {
var data interface{}
yaml.Unmarshal([]byte("foo: bar"), &data)
println(reflect.TypeOf(data).String())
}
This outputs:
map[string]interface {}
You'll gets a structure consisting of maps, slices or scalar types depending on the input. Due to Go's static type system, you need to use reflection / casts to access the actual values.
Alternatively, you can unmarshal into a Node:
package main
import (
"gopkg.in/yaml.v3"
)
func main() {
var data yaml.Node
yaml.Unmarshal([]byte("foo: bar"), &data)
println(data.Kind)
}
This prints 1, which is a DocumentNode. Non-scalar nodes hold their children in the Content field; you can walk through the structure by checking each Node's Kind and descend for those nodes.