Menu
Coddy logo textTech

External Files

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 1 of 107.

In Go, you can split your code across multiple .go files within the same package. All files sharing the same package declaration can access each other's functions and types directly — no import needed.

// helper.go
package main

func Add(a, b int) int {
    return a + b
}

Use the function in another file of the same package

// main.go
package main

import "fmt"

func main() {
    result := Add(3, 5)
    fmt.Println(result) // Output: 8
}

Both files declare package main, so Add is available in main.go without any import. This lets you organize code into logical files while keeping them in the same package.

challenge icon

Challenge

Easy

Create two functions in helper.go that are used by main.go:

  • Add — takes two int parameters and returns their sum
  • Subtract — takes two int parameters and returns their difference

Cheat sheet

You can split your code across multiple .go files within the same package. All files sharing the same package declaration can access each other's functions and types directly without importing.

// helper.go
package main

func Add(a, b int) int {
    return a + b
}
// main.go
package main

import "fmt"

func main() {
    result := Add(3, 5)
    fmt.Println(result) // Output: 8
}

Both files declare package main, so functions defined in one file are available in the other without any import statement.

Try it yourself

package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a, &b)

    fmt.Printf("Sum: %d\n", Add(a, b))
    fmt.Printf("Difference: %d\n", Subtract(a, b))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming