Skip to content

How to run existing program with yaegi cli and extend program’s functionality #1505

Answered by mpl
KiranSatyaRaj asked this question in Q&A
Discussion options

You must be logged in to vote

Hi.

what you're trying to do cannot work, because the nums variable from the main is local to the main function, it is not a global scope variable. So it is unknown when you're trying to give it as an argument to the median func(). It's as if you were trying to run that code:

package main

import (
	"fmt"
	"sort"
)

func oldmain() {
	nums := []int{1, 2, 3, 4, 5}
	sum := 0
	for _, num := range nums {
		sum += num
	}
	average := float64(sum) / float64(len(nums))
	fmt.Println("The average is", average)
}

func median(nums []int) float64 {
	sorted := make([]int, len(nums))
	copy(sorted, nums)
	sort.Ints(sorted)
	length := len(sorted)
	if length%2 == 0 {
		return float64(sorted[length/2]+sorted[(

Replies: 1 comment 12 replies

Comment options

You must be logged in to vote
12 replies
@KiranSatyaRaj
Comment options

@KiranSatyaRaj
Comment options

@mpl
Comment options

mpl Feb 2, 2023
Collaborator

@KiranSatyaRaj
Comment options

@KiranSatyaRaj
Comment options

Answer selected by mpl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants