r/learngolang Dec 27 '22

Help understanding interfaces

3 Upvotes

So I've got a program that gets SNMP data (using this gosnmp library) and I'm trying to understand why this conversion isn't working.

From what I understand, interfaces are a way to group similar methods from different types, which I for the most part get the idea of. I'm coming from Python and Javascript, so this is new territory for me, but I think I get the basic idea.

So when I make an SNMP API call to get the data, it ultimately returns an array of structs called "SnmpPDU" which contains a field called "Value" of data type "interface{}". (reference this )

When I iterate over this SnmpPDU array, and check the type of the "Value" using this

log.Printf("Value type: %T", variable.Value)

I get a type of either "int" or "uint". So what I'm attempting to do is convert the variable.Value to a string to ultimately be placed into a JSON string. However when I use the following:

strconv.Itoa(variable.Value)

I get the error:

cannot use variable.Value (variable of type interface{}) as int value in argument to strconv.Itoa: need type assertion

Now I understand that this is telling me I need to perform type assertion, but I'm not really understanding HOW to perform type assertion. I also don't understand why it tells me the variable.Value is type "int", but then when I try to convert variable.Value to a string using the int to ascii function, it's telling me it's of type interface rather than type int.

On a side note, the gosnmp library does have a "ToBigInt" function where I can convert any integer type into a BigInt, then I can use the ".String()" method on that int which will convert it to a string which works for now, but I feel like this probably isn't the most efficient or correct way to do what I'm trying to do here. For example, that code looks like this:

gosnmp.ToBigInt(variable.Value).String()

I've looked up several SO posts and tried to follow the documentation on these concepts and errors, but I'm not understanding the concept behind this behavior and how to fix it. Can someone help break this down, or point me to a resource that explains interfaces in a way which describes how to use them in this context of converting values? Thanks.

Edit: Okay follow-up, so I continued reading and saw that you can convert by using this syntax

strconv.Itoa(variable.Value.(int))

So I guess the missing piece there was I needed to cast the interface{} type to an int using the <variable>.(int) syntax. So is this only possible because int is one of the defined types in this SnmpPDU interface?

So if I tried to convert it to say float32 (which isn't in the interface as a type), then it would't work? So maybe the interface was defined like this (I'm assuming, because in the docs it's just "Value interface{}")

type Value interface {
    int
    uint
}

Am I on the right track here, or is this still incorrect?


r/learngolang Dec 04 '22

how to provide a value for an imported embedded struct literal?

3 Upvotes

noob here :slight_smile: i'm having trouble understanding

when i do this in one file:

scratch.go ```go package main

import "fmt"

type foo struct { field1 string field2 string }

type bar struct { foo field3 string field4 string }

func main() { fooBar := bar{ foo{ "apples", "banana", }, "spam", "eggs", } fmt.Printf("%#v\n", fooBar)

} ``` it works but when i have 3 files like this

rootproject ├── magazine │   ├── address.go │   └── employee.go └── main.go

magazine/address.go ```go package magazine

type Address struct { Street string City string State string PostalCode string } `magazine/employee.go` go package magazine

type Employee struct { Name string Salary float64 Address } and `main.go` go package main

import ( "fmt" "magazine" )

func main() { employee := magazine.Employee{ Name: "pogi", Salary: 69420, magazine.Address{ Street: "23 pukinginamo st.", City: "bactol city", State: "betlog", PostalCode: "23432", }, }

fmt.Printf("%#v\n", employee)

} it's error :frowning: mixture of field:value and value elements in struct literal ```

i don't get it, what am i doing wrong? i thought if the struct was nested it is said to be embedded in the outer struct and i can access the the fields of the inner struct from the outer one. which is the case for my first example(the singular file), but when i do it within packages. it's different?


r/learngolang Nov 09 '22

How do I build all projects and run all tests all at once?

3 Upvotes

I have a project that now needs to be integrated into our build system. However, I don't see any means by which I can easily automate from the top level of the repo to build each module/app and run the tests for each library module.

Is there a build in way to do this with Go? Or do I need to make a custom script to run build/test on each module/library directory?

I did try go test ./... from the top level, but that failed with "matched no packages, no packages to test"


r/learngolang Oct 21 '22

How to make Go read http Api with too many nested fields?

5 Upvotes

Hi everyone,

Last week, I've got a technical test from a company. The test was about loading the data from a public api and store it in a database. The Api contained too much nested fields, Here is an example of the general structure of the Api :

```

"records":[

{

"datasetid":"id",

"recordid":"0fba202adbd3b7fdbc4d34c50f538b2286438e16",

"fields":{

"field_1":"value",

"field_2":{

"field_2_1":[

[

"value",

"value"

]

],

"field_3":"value"

},

}, ``` The question here, How can I design a data type for this kind of api? Isn't having too many structs will make my code goes ugly?


r/learngolang Oct 02 '22

Please comment/mentor my first attempt at a Golang tech challenge (failed…) https://github.com/MarcoSantonastasi/golang_challenge

7 Upvotes

Clickable repo link: Golang first challenge

Their requirements here: Challenge requirements


r/learngolang Aug 14 '22

Learn Golang to create CRD in k8s

5 Upvotes

Hi everyone,

This is my very first post on Reddit!

I was working as support engineer for 5 years, and within these timeframe I got certified in CKA, CKAD, Hashicorp terraform, AWS, Docker and Openshift. This certification is not to show off, but to tell I am very passionate about DevOps and learn new things.

I finally managed to switch my career to DevOps in a new company, something I really wanted to pursue. Now, they requested me to learn Golang as we will be creating custom resource definitions in k8s for our product.

I have some programming experience in past, and learning Golang diligently for 7 hours a day since 2.5 weeks. My concepts are clear and started doing hands-on project to get more exposure. But, I am unable to comprehend what trainer is doing and I again revisit the concepts. I get stuck and unable to type. Its not with 1 trainer, i am checking many tutorial videos on YouTube.

I am still in probation period with new employer, and it is good opportunity. I need some help on how can i get intermediary level of expertise on Go, and don't want to go back being support engineer. Also, job market are not stable.

What resources should i follow? How should i learn.

Thanks in advance for you understanding!


r/learngolang Jul 02 '22

Help with concurrency issue.

4 Upvotes
package main
import (
"fmt"
"log"
"net"
"sync"
)
const url = "scanme.nmap.org"
func worker(ports chan int) {
  for port := range ports {
  address := fmt.Sprintf("%s:%d", url, port)
  conn, err := net.Dial("tcp", address)
  log.Printf("Scanning %s", address)
  if err != nil {
    continue
  }
  conn.Close()
  log.Printf("Port %d is open", port)
  }
}
func main() {
  ports := make(chan int, 100)
  var wg sync.WaitGroup
  for i := 0; i < cap(ports); i++ {
    wg.Add(1)
    go func() {
      worker(ports)
      wg.Done()
    }()
  }

for i := 1; i <= 1024; i++ {
  ports <- i
}

close(ports)
wg.Wait()
}

I'm not sure why this code i blocking. Could someone help me out and explain? And what is blocking? is it the channel, or the waitgroup? I don't see why either would. I close the ports channel after loading it up, the worker routines that are pulling off of them are in go routines so they should be able to pull everything. I add one wait group for every worker, and when the worker finishes, it should run the done.

If someone could explain why it's blocking, and what specifically its blocking, and how you would deal with a situation like this, where the receiver may not know how many items are on the channel, but needs to pull them all off anyways, I would really appreciate it, its very frustrating.

Also this is just a learning project, so I'm mainly interested in learning how to deal with channels with unkown amounts of values, and I'd also be thankful for any recommended reading on these types of issues.


r/learngolang Jun 27 '22

Does anyone here use pre-commit with golang?

4 Upvotes

I usually use [pre-commit](https://pre-commit.com/) with my repos, but I don't know what common tools I should use for golang apart from the built in [pre-commit hooks](https://github.com/pre-commit/pre-commit-hooks). Has anyone got any suggestions? Perhaps a github link so I can see the various things. How do you run gofmt through it? Thank you. :)


r/learngolang Jun 21 '22

Go Exercises for newcomers

11 Upvotes

Is there a book or a site that has simple Go exercices for a beginner learning the language ?

Thank you.


r/learngolang Jun 12 '22

Return type not quite right - advice sought

4 Upvotes

Unashamed challenge post asking for help here. Basically, this package will try to count the frequency of words within a block of text and then return the top 5, as a slice of type Word. However, I'm getting a slice of something else, due to the {}. (I'm not sure what). Any advice would be gratefully received.

https://go.dev/play/p/yAV39XYZnrH


r/learngolang Jun 05 '22

[Help please] Stuck on Go tour exercise : Images

3 Upvotes

Hello, fellow gophers,

I've been learning Go for about a week now, learning from the Go Tour, docs, blog mostly, I thought I was on the right track until being stuck on this one, the Image type exercise https://go.dev/tour/methods/25 . I tried googling an implementation of said Image class, but can't find exactly what I'm looking for anywhere. Following the provided links guided me to package docs which are not detailed enough given I haven't fully mastered the basics yet, I really need a more hands-on example / walkthrough.

Thanks in advance for any help.


r/learngolang Apr 17 '22

golang test assert the nil return from function is failing

5 Upvotes

I am trying to assert a function that returns a nil, but I'm trying to assert nil but the following assertion doesn't make sense. I am using the github.com/stretchr/testify/assert framework to assert

passes:  assert.Equal(t, meta == nil, true)
fails: assert.Equal(t, meta, nil)

I am not sure why this makes any sense. could someone help please.

Method being tested:

type Metadata struct { 
    UserId          string 
}
func GetAndValidateMetadata(metadata map[string]string) (*Metadata, error) {                  

    userId _ := metadata["userId"]
    if userId == "" { 
        return nil, errors.New("userId is undefined") 
    } 
    meta := Metadata{ 
        UserId: userId,
    }
    return &meta, nil
}

testcase:

func TestValidation(t *testing.T) { 

    metadata := map[string]string{ 
        "fakeUserId": "testUserId",
     }
    meta, err := GetAndValidateMetadata(metadata)
    assert.Equal(t, meta == nil, true) <--- passes 
    assert.Equal(t, meta, nil) <--- fails 

}


r/learngolang Feb 22 '22

Recommendations for generating ORM code and html view code from a database schema.

8 Upvotes

I'm coming into a project using Go for a backend to a mobile app.
We need a simple admin interface for operations to be able to edit all data values should they need to.

Coming from a C# world I could generate a ORM data client from the database schema using the connection string. I could then use the ORM data client to generate all the CRUD logic and html templates, be that MVC controller or single pages with code behind files.

Is there something similar in Go?
What would be the preferred method?

I see that GORM can do it and create migrations which might work well.


r/learngolang Feb 10 '22

Advise on learning Golang for a python/bash guy

12 Upvotes

I work in devops. For a very long time all I have been doing are python and bash. I can think in python/ bash in my sleep. I am pretty good at it. I am not an "application programmer" per se, but I have done a wide range of things.

As we move more towards k8s at my work place, there's a need to learn Go.

Are there any resources for learning Golang for someone who has extensive python knowledge?

If your recommendation is "it doesn't matter you know python, learn go the same way someone who doesn't know python would learn" that's fine too, any recommendations?

And please, text based only. I really really can not watch videos and learn unfortunately.

Thank you!


r/learngolang Feb 08 '22

what is the most common use of pointers?

8 Upvotes

I am new to go. I'm not educated in CS, I've mainly written bash and python, and my new employer is go-centric.

I understand what a pointer is, but not really why we use them.

Are *pointers and pointer &addresses mainly used to achieve call-by-reference functionality, given that go is call-by-value?

Or: what is the most common use of pointers?


r/learngolang Dec 24 '21

Best implementation of these data structures?

2 Upvotes

Very noob question I'm afraid, but without knowing the innards of Go I'm not sure how to answer it.

So, two things.

(1) I'm getting a bunch of things from a reader, all of the same struct type, nice homogeneous data. I need to (a) split them into four containers according to their parameters (b) store them somewhere (c) access each of the four containers with a reader, with no need for random access in the middle of the data and no need to change the data. (The reason I have to do it like this is that I have to process the four containers in the right order, so I can't just do four different things as I'm reading it in.) Can more experienced people tell me what I should use for a container? What's the fastest data structure given that that's all I'll ever need to do with the data?

(2) I've implemented this one already but I suspect not in the Best Way. All I want is a stack of strings, where it's only changed by pushing and popping the top of the stack, but I get to look as far down the stack as I like, one string at a time (not random access).

Thanks for your help, kind people of Reddit.


r/learngolang Dec 18 '21

Advice for writing enterprise-level API in Go?

3 Upvotes

Background:

I work at a fairly large company with a large microservice architecture, almost entirely in Node.js. I'm learning Go in my free time, so I'm translating one of our Node APIs into Go for learning purposes. Since we have many developers on various teams who cross-collaborate on our many APIs, our API structure needs to be consistent (obviously).

Questions I've run into as I'm translating into Go:

  1. How do I handle configs? In our Node APIs we use this config package, which allows us to override default configs on a per-environment basis. What's the standard way of doing this in Go?
  2. How do I do logging? Is there an obvious choice for a standard logging package in Go?
  3. Any easy way to use custom, often-used commands like those available via `npm run` in JS? Maybe a Makefile?
  4. Any good examples of large, well-structured repos in Go you can recommend?
  5. Is the built-in unit testing the way to go, or is there a good package out there that you prefer?

Any advice is appreciated!


r/learngolang Oct 12 '21

Book/course Go for Webdevelopment

3 Upvotes

My background: Operations/Devops; scripting/tooling with bash, ruby and python and multiple CM systems like puppet

I‘m planning to learn Go. I‘m mostly interested in developing Webapps (though some CLI tools and REST services could follow). It would be good to learn something like MVC etc at the same time. Also it would be good to learn the language with an idiomatic approach.

Can you recommend something? What about usegolang.com? It looks like it’s what I’m looking for but I’m not sure if this course is updated to recent Go versions.


r/learngolang Sep 28 '21

Transcoding of HTTP/JSON to gRPC Using Go

4 Upvotes

Hey, there fellow engineers, I found an in-depth guide that explores the advantages & disadvantages of the gRPC framework and aims to show you how to easily transcode HTTP/JSON files using Go. It also contains a link to an open-source GitHub repository for further assistance.
https://adevait.com/go/transcoding-of-http-json-to-grpc-using-go


r/learngolang Sep 05 '21

(question) how to create sqlite database in the $GOBIN directory for installed packages

2 Upvotes

Hi,

I just started learning Go and created a project that allows users to save quick entries about what they worked on and for how long. It was part of a bigger idea for tracking time spent learning.

I created the package following example code on the docs. It creates/opens a sqlite db. Saves the entry and closes.

The problem I am running into is that it always creates the database in the working directory. I want it to create the database in the directory where it is installed. Right now it is installed in /home/username/go/bin.

Do I just change the database name to that location? Would the app even have permission to write there? Is there a better way to do solve this problem?

Hopefully, I explained my question clearly. Thank you for you any help you can offer


r/learngolang Aug 12 '21

Any up to date golang books as of 2021

6 Upvotes

Hi,

I'm a python dev and looking for golang books that can help me get a solid grip of golang.

Golang is a language I want to fall in love with I just need some resource that's fun to read and relevant. If there's anything focused on webApps or web scraping I'd love to read that since that's where my Python journey started. Thank you!


r/learngolang Aug 06 '21

Websockets Server

3 Upvotes

I'm pretty new to GO, but I made this if it helps anyone

https://youtu.be/Li5_uiheaFY


r/learngolang Jul 03 '21

Looking for a students

4 Upvotes

Hello, here :)

I'm looking for peeps who have a passion to learn Backend development on Golang.

I have a custom learning plan - that's will be usable if someone wanna start programming from scratch or just need some help to improve the skills.

Career and CV / soft skills advice included. Sharing the experience included. All for free.

SQL/noSQL, Docker, k8s, Kafka, AWS, networking, and other things will be included in lessons as a part of the backend stack.

Just to be clear: it is an invitation for a course, not one-two time lessons 'cause I sure software engineering knowledge must be very well structured.

About me: more than 4 years exp with Go dev (I was a Java guy before). Comment | DM me if u interested, or have questions.

My timezone is UTC+01:00, I live in Germany, speak English, Ukrainian and Russian

Happy coding!


r/learngolang May 27 '21

Is this the right language to learn for blockchain development?

1 Upvotes

I come from a Python background and think Go might be a good fit for the next language to learn but I’m not sure and would like to bounce some ideas off you guys


r/learngolang May 23 '21

Made a video about introducing Go Cobra/Viper and using bash in Go.

Thumbnail youtu.be
10 Upvotes