Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom package is not in golang std

Tags:

go

Trying to run my golang code and it exits with this error:

main.go:5:2: package lesson/students is not in std (C:\Program Files\Go\src\lesson\students)

Can't find info in google, help me please(

Project structure

project/
    lesson/
        students.go
    main.go
    go.mod

main.go

package main

import (
    "fmt"
    "lesson/students"
)

func main() {
    student1 := students.Student{}
    fmt.Println(student1)
}

lesson/students.go

package students

type Student struct {
    Name string
    age  int
}

go.mod created by go mod init lesson

like image 574
DJsega1 Avatar asked Sep 03 '25 04:09

DJsega1


1 Answers

in your project/go.mod you can find something like

module project

go 1.XX.X

this mod file knows the path to the dependencies being called by the main.go, taking from the name you gave to the package project and pointing to the current directory onwards. You could say it sets the working dir of the package, and the scope of declared stuff is given by the subfolders structure.

Lets say you want to use the Students struct in the main.go you would need to import project/lesson then access it through lesson.Student({...}), it doesn't matter if the Student is in the project/lesson/students.go file or the project/lesson/anything.go file

package project

import (
    "fmt"

    "project/lesson"
)

func main() {
    fmt.Println(lesson.Student{Name: "John", Age: 25}) //will show {John 25}
}

btw Student.age should be Student.Age for it to be visible, also the student.go file should start with the package lesson statement

like image 136
Santiago G. Alegria Avatar answered Sep 05 '25 00:09

Santiago G. Alegria